![](/img/trans.png)
[英]Ruby (v 2.3.1) .each method on .split array not in any logical order
[英]Ruby .each method on Array from split string
我在对string.split结果产生的数组上使用.each方法时遇到麻烦
def my_function(str)
words = str.split
return words #=> good, morning
return words[words.count-1] #=> morning
words.each do |word|
return word
end
end
puts my_function("good morning") #=> good
使用任何多单词字符串,我只会得到第一个单词,而不是每个单词。 在这个例子中,我不明白为什么第二项明显存在于数组中时为什么我没有得到“好”和“早上”。
同样,使用while循环也可以得到相同的结果。
def my_function(str)
words = str.split
i = 0
while i < words.count
return word[i]
i += 1
end
puts my_function("good morning") # => good
任何帮助表示赞赏。 提前致谢!
您假设return words
将数组返回到外部的puts
函数,这是正确的。 但是,一旦返回,就离开该函数,并且永远不会返回,除非再次(明确地不是)再次显式调用my_function()
,在这种情况下,您将从函数的开头重新开始。
如果要在保留功能的同时打印值,则需要使用
def my_function(str)
words = str.split
puts words #=> good, morning
puts words[words.count-1] #=> morning
words.each do |word|
puts word # print "good" on 1st iteration, "morning" on 2nd
end
end
my_function("good morning")
ruby中的return语句用于从Ruby方法返回一个或多个值。 因此,您的方法将从return words
退出。
def my_function(str)
words = str.split
return words # method will exit from here, and not continue, but return value is an array(["good", "morning"]).
return words[words.count-1] #=> morning
....
end
puts my_function("good morning")
输出:
good
morning
如果要使用each
方法来输出单词,则可以执行以下操作:
def my_function(str)
str.split.each do |word|
puts word
end
end
要么
def my_function(str)
str.split.each { |word| puts word }
end
my_function("good morning")
输出:
good
morning
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.