搜索Ruby哈希值?

时间:2012-10-18 09:57:36

标签: ruby

尝试通过散列搜索值,我之前尝试过的方法都没有用。

def input
  @search_term = STDIN.gets.chomp
end

def execute
  @reader.searchKey(@search_term).each{|b| puts b}
end

def searchKey(search_term)
  puts books_catalogue.has_value?(search_term)
end

2 个答案:

答案 0 :(得分:1)

hash = {foo: 'val', bar: 'other_val', bak: 'val'}
selected_hash = hash.select { |k,v| v == 'val' } # => {foo: 'val', bak: 'val'}
selected_hash.keys # => [:foo, :bak]

所以方法如下:

def search_key(value)
  @hash.select { |k, v| v == value }.keys
end

答案 1 :(得分:0)

试试这个:

hash = {a: 1, b: 2, c: 2}
value_to_search_for = 2
hash.select {|_,value| value == value_to_search_for}
# output is {b: 2, c: 2}