Ruby:匹配哈希中的键以返回相应的键+值

Jee*_*rma 2 ruby hash

我有哈希

hash = {"stars"=>"in the galaxy", "fin"=>"is for fish", "fish"=>"has fins"}
Run Code Online (Sandbox Code Playgroud)

现在我有一个find方法

def find(value)
    if hash.empty? == true
      return {}
    else
     return  hash
    end
  end
Run Code Online (Sandbox Code Playgroud)

现在我想做的是 - 当执行时find("fi"),我希望该方法返回包含fi在键中的所有哈希键+值.所以这样的输出看起来像 -

{"fin"=>"is for fish", "fish"=>"has fins"}
Run Code Online (Sandbox Code Playgroud)

请注意"fi"不固定.它可以是任何东西.由于Find方法接受一个参数value.

任何帮助或建议是值得赞赏的.我试过hash #select.但是没那么有帮助.我不确定在这里使用什么.

roh*_*t89 8

hash.select {|k, _| k.include? str}str你要找的字符串在哪里.


the*_*Man 6

我会用以下的东西:

hash = {"stars"=>"in the galaxy", "fin"=>"is for fish", "fish"=>"has fins"}
pattern = 'fi'
hash.select{ |k,v| k[pattern] }
# => {"fin"=>"is for fish", "fish"=>"has fins"}
Run Code Online (Sandbox Code Playgroud)