问题描述
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
在上面rails迁移代码中:books是用符号代表参数吗? :title :price :string这些都是要干什么捏? 我知道ruby中的符号是用来替代字符串节省内存空间 可是这个情形下依然不知道是什么意思啊 求大神解答
<p class='row collapse'> <p class='small-3 columns'> <%= f.label :name, class: 'right inline' %> </p> <p class='small-9 columns'><%= f.text_field :name %></p></p><p class='row collapse'> <p class='small-3 columns'> <%= f.label :price, class: 'right inline', title: 'Price in USD', data: {tooltip: true} %> </p> <p class='small-9 columns'><%= f.text_field :price %></p></p><p class='row collapse'> <p class='small-9 small-offset-3 columns'><%= f.submit %></p></p>
还有在erb中也出现了ruby符号的奇怪用法 f.label :price 是要用:price 去代替f.label吗? 急求大神解答 纠结了几天了
问题解答
回答1:ruby中的:xxx表示一个symbol。
你可以把symbol 理解 成 string,但是他们并不完全一样。
symbol是不变的。
首先,ruby中的所有东西都是对象,每个对象都有一个唯一的object_id代表他在内存中的物理位置(但是不是直接访问就是这个对象的)。
但是,有一些东西是例外的,比如整数,你会发现,相同整数的object_id是相同的,这是ruby节约资源的一种做法。
VALUErb_obj_id(VALUE obj){ if (TYPE(obj) == T_SYMBOL) { return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG; } if (SPECIAL_CONST_P(obj)) { return LONG2NUM((long)obj); } return (VALUE)((long)obj|FIXNUM_FLAG);}
这是ruby的实现,symbol和常量一样,相同的symbol使用相同的object_id,也就是他们在内存当中的位置是一样的。( 常量的object_id就直接反应了常量的值,在处理的时候也是特殊处理的)。
至于上面的代码。ruby当中函数调用的括号是可以省略的,比如 f.label :price 实际上是 f.label( :price)同时,hash的{}也是可以省略的,这就是你看的的:xxx=>xxx,xxx=>xxx或者xxx:xxx,xxx:xxx,他们实际上是{:xxx=>xxx,...}
:price是他的一个参数而已。
所以就出现了
f.label :name, class: 'right inline'
这样的代码,他的意思是,
f.label (:name, {:class => 'right inline'})
这样,他就会创建一个label在form f下面,name是:name,而html标签中的class是'right inline'。
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