0

I`m new to rails, so that question may be stupid. I have seen a lot of code like this

method do |x|
 x.something
 x.blabla
end

For example some snippet from migrate

create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end  

What happens here ? |t| is passed to create_table method or ? I can`t fugure out

ruby_newbie
  • 129
  • 1
  • 2
  • 7
  • possible duplicate of [Blocks & Procs in Ruby](http://stackoverflow.com/questions/3560571/blocks-procs-in-ruby) – Nakilon Jan 28 '11 at 19:25
  • Also: http://stackoverflow.com/questions/4783166/whats-the-gain-i-can-have-with-blocks-over-regular-methods – Nakilon Jan 28 '11 at 19:25
  • Also: don't answer duplicates, If really you have nothing to add to existing answers. – Nakilon Jan 28 '11 at 19:26

1 Answers1

2

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]).

user229044
  • 232,980
  • 40
  • 330
  • 338