ruby-on-rails - ruby中do关键字的用法

 我们要走下去一直的 发布于 2022-10-25 08:25
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
  end
end
create_table :books do |t|

这一句 没有迭代操作 为什么会有 ruby do |t|这句呢 这里的 ruby do |t|到底是什么意思? 求高人解答

3 个回答
  • do ... end 等价于{ ... },是一个block,ruby方法可以接block参数

    2022-10-26 14:35 回答
  • 在这里:/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
        # 创建这个表
        # ...
      end
    end
    

    关于迭代器更具体的用法可以看看这个吧:http://blog.csdn.net/classwang/article/details/4692856

    2022-10-26 14:35 回答
  • 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
    
    2022-10-26 14:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有