来自拆分字符串的Array上的Ruby .each方法

时间:2015-05-22 03:26:54

标签: arrays ruby while-loop split each

我在使用.each方法在数组上使用string.split

时遇到问题
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

感谢任何帮助。提前谢谢!

2 个答案:

答案 0 :(得分:1)

您假设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")

答案 1 :(得分:1)

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