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 Foundations Blocks Examples

Allen Wang
Allen Wang
3,439 Points

What does the |a| do at the end of the how_many.times call?

I'm still having some difficulty understanding what is going on when there is a variable surrounded by || such as |a|, or when you have a block written as {|var| some operation on var}

1 Answer

Effectively what you're doing when you pass a block to a method is defining a temporary anonymous (as in it has no name so you can't call it later on) function. The variables between the pipes ("|foo|") are the arguments that block takes. If we look at array#each we see that it will attempt to pass one argument to our block, item, so we should set up our block to accept a single parameter:

array.each do |item|
  puts item
end

Alternatively if we look at hash#each it will attempt to pass two variables to our block each time it is called, the key and that key's value.

hash.each do |key, value|
  puts "The value for #{key} is #{value}"
end

Hope that helps!