Reputation:
I have a question about Ruby return values which is baffling me.
I have written a method which takes an array as an argument and formats the array into a list as follows:
def list(array)
array.each { |name, age| puts name + " is #{age} years old" }
end
Let's say the array is [["Amy", 6], ["Tabitha", 5], ["Marcus", 9]]
.
I want this list method to return the strings in the do/end block, and not return the array. However, the return value is always an array.
I have tried assigning the block to a variable and returning the variable but it doesn't work. I also tried replacing puts
with return but that then exits the method after the first iteration. Can't seem to work out what the problem is?
Sorry if this is a really silly question - I haven't come across it before.
Any input much appreciated, thanks! :)
Upvotes: 1
Views: 1572
Reputation: 11
The return value of each
is the list. The function returns that list since it is the last returnable instruction. You need to use the map
method in the following way:
def how_old(people)
people.map { |name, age| "#{name} is #{age} years old" }
end
Upvotes: 0
Reputation: 4589
You want map
, not each
. map
is like each
, except it returns the result of each block evaluation. each
returns the original array.
Also, and your main error here is that puts
display something in the console, nothing else.
Your final code would be :
def list(array)
array.map { |name, age| "#{name} is #{age} years old" }
end
Upvotes: 6