使用Ruby中的部分哈希搜索哈希数组

时间:2012-06-12 06:42:33

标签: ruby

给出哈希

z = [{'a' => 1, 'b' => 2}, {'a' => 3, 'b' => 4}, {'a' => 1, 'b' => 4}]

如何搜索搜索参数本身是否为散列,例如

{'a' => 3}

这样我可以做z.find_by_hash({'a'=> 3})之类的事情让它返回

{'a' => 3, 'b' => 4}

并获取z.find_by_hash({'a'=> 1})等数组的集合,以便它返回

[{'a' => 1, 'b' => 2}, {'a' => 1, 'b => 4}]

由于

4 个答案:

答案 0 :(得分:1)

你可以这样做:

class Array
  def find_by_hash(hash)
    self.select { |h| h.includes_hash?(hash) }
  end
end

class Hash
  def includes_hash?(other)
    included = true

    other.each do |key, value|
      included &= self[key] == other[key]
    end

    included
  end
end

这通过一种方法扩展Hash,以确定Hash是否包含另一个(具有多个键和值)。使用您想要的方法扩展Array,但这是一种更通用的方法,因为您可以这样做:

ary = [ {:a => 1, :b => 3, :c => 5}, {:a => 5, :b => 2, :c => 8} ]
ary.find_by_hash( { :a => 1, :c => 5 } )

注意:您还应该考虑将Symbol用于Hash密钥,因为这是Ruby中的常见做法,但我的方法也适用于您的密钥。

答案 1 :(得分:0)

z = [{'a' => 1, 'b' => 2}, {'a' => 3, 'b' => 4}, {'a' => 1, 'b' => 4}]

class Array
  def search_hash(hash)
    key = hash.keys.first
    value = hash.values.first
    select { |h| h[key] == value }
  end
end

z.search_hash({'a' => 3}) #=> [{"a"=>3, "b"=>4}]

或者您可以使用大括号输入

z.search_hash('a' => 3)

答案 2 :(得分:0)

基本上你需要的是这样的东西:

class Array
  def find_by_hash(h)
    h.collect_concat  do |key, value| 
      self.select{|h| h[key] == value}
    end
  end 
end

答案 3 :(得分:0)

我没有在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

结果:

sg552@siwei-moto:~/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