问题描述
class Books < ActiveRecord::Migration def self.up create_table :books do |t| t.column :title, :string, :limit => 32, :null => false t.column :price, :float t.column :subject_id, :integer t.column :description, :text t.column :created_at, :timestamp end end def self.down drop_table :books endend
create_table :books do |t|
这一句 没有迭代操作 为什么会有 ruby do |t|这句呢 这里的 ruby do |t|到底是什么意思? 求高人解答
问题解答
回答1:create_table :books do |t|
不是迭代而是回调。
关于Ruby的回调:http://stackoverflow.com/questions/1677861/how-to-implement-a-callback-in-ruby
关于Rails的Migration:http://guides.rubyonrails.org/migrations.html
如果你用jQuery做过Ajax的话,应该有类似这样的经验:
$.get('test.php', function(data){ alert('Data Loaded: ' + data);
$.get()方法的返回值是test.php的response body,第一个参数是请求的url,第二个参数就是回调函数,这个函数接受test.php的response body作为参数data的值,并通过弹窗显示。
这条Migration语句你可以这么理解。
# 创建了一个名为books的表create_table :books do |t| # t是create_table方法的返回值 t.column :title, :string, :limit => 32, :null => false # 创建一个列title,字符串,最大长度32,不为null t.column :price, :float # 创建一个列price,浮点型 t.column :subject_id, :integer # 创建一个列subject_id,整形 t.column :description, :text # 创建一个列description,文本 t.column :created_at, :timestamp # 创建一个列created_at,时间戳end回答2:
在这里:/q/1010000000266437 已经回过一遍了,再搬过来。
create_table :books do |t|
do|x|...end没有什么特殊的意义和{|x|}一样,只是代表一个block而已,这个代码中是有迭代出现的,他实际上是类似于:
File.open('xxx','xxx') do |f|f.write(...)end
的,当然这样也是合法的:
File.open('xxx','xxx') { |f| f.write(...)}
然后因为括号可以省略就变成上面的样子了。
对于ruby来说要实现这样的功能,只需要:
class Somethings#... def create_table(name) # 为创建这个表做一些准备…… # ... yield @table # 创建这个表 # ... endend
关于迭代器更具体的用法可以看看这个吧:http://blog.csdn.net/classwang/article/details/4692856
回答3:do ... end 等价于{ ... },是一个block,ruby方法可以接block参数