Ruby Ruby Loops Ruby Iteration Iteration With Each

David Besserman
David Besserman
3,963 Points

Please, can you give more explantions on the role of the argument in the each method ?

I don't understand how the argument work in the each method.

Thank you

2 Answers

Samuel Webb
Samuel Webb
25,362 Points

Array#each (or the each method) basically goes over each item in an array and does whatever code is in the code block. The argument passed in is the current item in the array that is being worked on. An easy way to get a better understanding is to go into IRB and put in the following code:

nums = [1,2,3,4,5,6,7,8,9,10]
nums.each do |num|
    puts num
end

What that does is it will run the puts method on each number since you're passing them in one at a time as the argument. Hopefully this helps.

Samuel Webb
Samuel Webb
25,362 Points

I think a better piece of code would be:

names = ['Sam', 'Mike', 'Tom', 'Robert', 'Kevin', 'Stan']
names.each do |name|
    puts "Hello #{name}"
end
Samuel Webb
Samuel Webb
25,362 Points

Here's the documentation just in case you want to check it out. It's not to detailed though. Documentation.