我沒有找到在API的方法,所以我認爲我們必須實現它是我們自己的。
(順便說一句,我認爲@megas'的做法是更好,更可讀的)通過TDD
代碼:
class SearchHashTest < Test::Unit::TestCase
def setup
@array_with_hash_elements = ArrayWithHashElements.new [{'a' => 1, 'b' => 2}, {'a' => 3, 'b' => 4}, {'a' => 1, 'b' => 4}]
end
def test_search_an_array_by_hash_parameter_and_return_single_hash
assert_equal({'a' => 3, 'b' => 4}, @array_with_hash_elements.search({'a'=>3}))
end
def test_search_an_array_by_hash_parameter_and_return_an_array
assert_equal([{'a' => 1, 'b' => 2}, {'a'=> 1, 'b' => 4}], @array_with_hash_elements.search({'a'=>1}))
end
end
執行代碼(僅用於演示,不生產)
class ArrayWithHashElements
def initialize some_array
@elements = some_array
end
def search(query_hash)
puts "search: #{query_hash.inspect}"
result = []
@elements.each do | array_element_in_hash_form|
query_hash.each_pair do | key, value |
if array_element_in_hash_form.has_key?(key) && array_element_in_hash_form[key] == value
puts "adding : #{array_element_in_hash_form.inspect} to result"
result << array_element_in_hash_form
end
end
result
end
return result.size != 1 ? result : result[0]
end
end
結果:
[email protected]:~/workspace/test$ ruby search_hash_test.rb
Loaded suite search_hash_test
Started
search: {"a"=>1}
adding : {"b"=>2, "a"=>1} to result
adding : {"b"=>4, "a"=>1} to result
.search: {"a"=>3}
adding : {"b"=>4, "a"=>3} to result
.
Finished in 0.000513 seconds.
2 tests, 2 assertions, 0 failures, 0 errors
謝謝。這是正確的,因爲它解決了在散列內搜索散列的根本問題 – globetrotter