我有散列是
hash = {"stars"=>"in the galaxy", "fin"=>"is for fish", "fish"=>"has fins"}
现在我有了一个查找方法
def find(value)
if hash.empty? == true
return {}
else
return hash
end
end
现在我想做的是 - 当执行 find("fi")
时,我希望该方法返回所有在键中包含 fi
的散列键+值.所以这样的输出看起来像 -
{"fin"=>"is for fish", "fish"=>"has fins"}
请注意“fi”不是固定的。它可以是任何东西。由于 Find 方法接受参数 value
。
如有任何帮助或建议,我们将不胜感激。我试过散列#select。但不是很有帮助。我不太确定在这里使用什么。
最佳答案
hash.select {|k, _| k.包括? str
其中 str
是您要查找的字符串。
关于Ruby:匹配散列中的键以返回相应的键+值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14814440/