Ruby .each 数组中拆分字符串的方法

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

对于任何多词字符串,我只得到第一个词,而不是每个词。在这个例子中,我不明白为什么当第二个项目明显存在于数组中时我没有得到 "good" 和 "morning"。

同样,使用 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 return 将数组发送给您的外部 puts 函数,这是正确的。然而,一旦你 return,你就离开了函数并且永远不会返回,除非你再次明确调用 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 语句用于 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