【问题标题】:How to get keys from hash ruby [closed]如何从哈希红宝石中获取密钥[关闭]
【发布时间】:2013-12-19 22:36:35
【问题描述】:

下一个代码搜索关键字是否出现在哈希值中,如果出现则打印yes, 但它在 codeacademy 控制台中运行良好,但在我的 Rubymine 中它给了我例外

NoMethodError: nil:NilClass 的未定义方法 `keys'

我尝试使用 each_key 方法,但结果相同。

arr = [
 { name: "2222", num:"4444 kod"},
 { name: "3222 kod", num:"43423444"},
 { name: "224422", num:"4442424"}
]

p = "kod"

arr.each do |frelancer|
frelancer.keys.each do |key|
    if frelancer[key].split(" ").include? (p)
        puts "yes"
    esle 
  puts "no"
    end

结束

你能给点建议吗?)

【问题讨论】:

  • 发布真实代码 - 显然这不会解析(例如esle
  • 你写的两个块的end 在哪里? Ruby =/= Python
  • 修复代码中的语法问题后,它对我来说运行良好并生成:no, yes, yes, no, no, no。有什么问题?
  • 正如@Alex 所说,更正esle 的拼写并在末尾再添加一个end,您的代码将正确运行。请注意,如果您正确格式化代码,您会注意到缺少的end。此外,为了使您的输出更有意义,请考虑在frelancer.keys.each do |key| 之后添加如下语句:print "frelancer[#{key}] = '#{frelancer[key]}' contains '#{p}': "

标签: ruby hash key


【解决方案1】:

你有两个错误:

  1. 你写的是esle而不是else
  2. 您缺少一个end 子句

【讨论】:

    【解决方案2】:

    您的区块需要end 关键字。并且else 应该拼写正确。

    arr.each do |frelancer|
      frelancer.keys.each do |key|
        if frelancer[key].split(" ").include? (p)
          puts "yes"
        else  
          puts "no"
        end  
      end  
    end  
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 2020-01-08
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      相关资源
      最近更新 更多