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! :)
eachexecutes the given block for each element of the array, then returns the array itself.putsreturns nil. You have to changeeachin tomapand removeputsfor this to work