Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,370 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,370 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,370 Points

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