【问题标题】:Unexpected return error in RubyRuby中的意外返回错误
【发布时间】:2015-05-09 03:53:32
【问题描述】:

我是学习 Ruby 的新手,在嵌套结构方面遇到了一些麻烦。

如果 :first 的值是“John”,我要做的是返回 :last name (“Doe”):

people = {
  :family => [
    {:first => "John", :last => "Doe"},
    {:first => "Jane", :last => "Smith"}
  ]
}

people[:family].each {|index| return index[:last] if index[:first] == "John"}

但是,控制台给了我这个错误:

test.rb:8:in `block in <main>': unexpected return (LocalJumpError)
from test.rb:8:in `each'
from test.rb:8:in `<main>'

当我在控制台中对此进行测试并将“return”替换为“puts”时,它会返回“Doe”,但由于某种原因,“return”似乎导致了“意外返回 (LocalJumpError)”。我怎样才能成功返回这个值而不遇到这个错误?

谢谢 - 非常感谢任何和所有帮助!

【问题讨论】:

  • 您在 .each 内部返回,这与从方法返回不同(因此,意外)。你想要.select{}

标签: ruby


【解决方案1】:

您不能在each 循环中使用return。您可以使用mapcollect 来返回一个姓氏数组,如下所示:

people[:family].collect {|index| index[:last] if index[:first] == "John"}
=> ["Doe", nil]

您还可以将匹配项推送到输出变量,如下所示:

output = []
people[:family].each {|index| output << index[:last] if index[:first] == "John"}
=> ["Doe"]

按照建议使用break,将返回第一个匹配项的字符串,但如果您有多个匹配项,它将不适合您。请参见下面的示例:

people = {
  :family => [
    {:first => "John", :last => "Doe"},
    {:first => "Jane", :last => "Smith"},
    {:first => "John", :last => "Galt"}
  ]
}
people[:family].each {|index| break index[:last] if index[:first] == "John"}
=> "Doe"

【讨论】:

    【解决方案2】:

    break 与值一起使用

    people = {
      :family => [
        {:first => "John", :last => "Doe"},
        {:first => "Jane", :last => "Smith"}
      ]
    }
    
    people[:family].each {|index| break index[:last] if index[:first] == "John"}
    

    【讨论】:

      【解决方案3】:

      return需要在方法内部使用:

      def foo
        # your code
      end
      
      foo # => "Doe"
      

      【讨论】:

      【解决方案4】:
      puts people[:family].find({}) {|index| index[:first] == "John"}[:last]
      

      【讨论】:

        猜你喜欢
        • 2016-08-10
        • 2022-11-21
        • 2019-09-10
        • 1970-01-01
        • 2018-12-28
        • 2015-08-23
        • 1970-01-01
        • 1970-01-01
        • 2012-06-19
        相关资源
        最近更新 更多