1

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!

3
  • return immediately exits the function. What are you trying to accomplish with the return statement? Commented May 22, 2015 at 3:31
  • In the first example, with return words, the array is returned. Using p my_function("good morning") to print is more clear. Commented May 22, 2015 at 3:31
  • What is your expected output? Commented May 22, 2015 at 3:33

2 Answers 2

1

The return statement in ruby is used to return one or more values from a Ruby Method. So your method will exit from 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")

output:

good
morning

if you want to use each method to output words, you can do like this:

def my_function(str)
    str.split.each do |word|
        puts word
    end
end

or

def my_function(str)
    str.split.each { |word| puts word }
end

my_function("good morning")

output:

good
morning
Sign up to request clarification or add additional context in comments.

Comments

1

You are assuming that return words returns the array to your outer puts function which is true. However once you return, you leave the function and never go back unless you explicitly call my_function() again (which you aren't) in which case you would start from the beginning of the function again.

If you want to print the value while staying in the function you will need to use

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.