小编Jee*_*rma的帖子

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

我有哈希

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.但是没那么有帮助.我不确定在这里使用什么.

ruby hash

2
推荐指数
2
解决办法
6484
查看次数

标签 统计

hash ×1

ruby ×1