I'm having trouble using the .each method on an array that results of a 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
With any multi-word string, I only get the 1st word, not each of the words. With this example, I don't understand why I don't get "good" and "morning" when the 2nd item clearly exists in the array.
Similarly, using a while loop gave me the same result.
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
Any help is appreciated. Thanks in advance!
returnimmediately exits the function. What are you trying to accomplish with thereturnstatement?return words, the array is returned. Usingp my_function("good morning")to print is more clear.