Weird (for me) using of methods in Rails
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
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])
.
精彩评论