我是学习Ruby的新手,并且在嵌套结构方面遇到了一些麻烦。
我想要做的是返回:姓氏(" Doe")如果值为:first是" John":
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>'
当我在控制台中对此进行测试并更换&#39;返回&#39;通过&#39; puts&#39;,它让我回归&#34; Doe&#34;但出于某种原因,他们会回归&#39;似乎导致意外的返回(LocalJumpError)&#39;。如何在不遇到此错误的情况下成功返回此值?
谢谢 - 非常感谢任何和所有帮助!
答案 0 :(得分:1)
将break
与值
people = {
:family => [
{:first => "John", :last => "Doe"},
{:first => "Jane", :last => "Smith"}
]
}
people[:family].each {|index| break index[:last] if index[:first] == "John"}
答案 1 :(得分:1)
您无法在return
循环中使用each
。您可以使用map
或collect
返回姓氏数组,如下所示:
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 :(得分:0)
return
:
def foo
# your code
end
foo # => "Doe"
答案 3 :(得分:0)
puts people[:family].find({}) {|index| index[:first] == "John"}[:last]