The |x|
is a parameter being passed to the block. It is a feature of Ruby, not specific to Ruby on Rails.
Here's a very contrived example of how you might implement a function which accepts a block:
# invoke proc on each element of the items array
def each(items, &proc)
for i in (0...items.length)
proc.call(items[i])
end
end
my_array = [1,2,3];
# call 'each', passing in items and a block which prints the element
each my_array do |i|
puts i
end
Effectively, you're invoking each
and passing it two things: An array (my_array
) and a block of code to execute. Internally each
loops over each item in the array and invokes the block on that item. The block receives a single parameter, |i|
, which is populated by each
when it calls proc: proc.call(items[i])
.