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
在上麵rails遷移代碼中:books是用符號(hào)代表參數(shù)嗎? :title :price :string這些都是要幹什麼捏? 我知道ruby中的符號(hào)是用來(lái)替代字符串節(jié)省內(nèi)存空間 可是這個(gè)情形下依然不知道是什麼意思啊 求大神解答
<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中也出現(xiàn)了ruby符號(hào)的奇怪用法 f.label :price 是要用:price 去代替f.label嗎? 急求大神解答 糾結(jié)了幾天了
擁有18年軟件開(kāi)發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
ruby中的:xxx表示一個(gè)symbol。
你可以把symbol 理解 成 string,但是他們並不完全一樣。
symbol是不變的。
首先,ruby中的所有東西都是物件,每個(gè)物件都有一個(gè)唯一的object_id代表他在記憶體中的物理位置(但是不是直接存取就是這個(gè)物件的)。
但是,有些東西是例外的,例如整數(shù),你會(huì)發(fā)現(xiàn),相同整數(shù)的object_id是相同的,這是ruby節(jié)約資源的一種做法。
VALUE
rb_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的實(shí)現(xiàn),symbol和常數(shù)一樣,相同的symbol使用相同的object_id,也就是他們?cè)谟洃涹w當(dāng)中的位置是一樣的。 ( 常數(shù)的object_id就直接反應(yīng)了常數(shù)的值,在處理的時(shí)候也是特殊處理的)。
至於上面的程式碼。 ruby當(dāng)中函數(shù)呼叫的括號(hào)是可以省略的,例如 f.label :price 其實(shí)是 f.label( :price) 同時(shí),hash的{}也是可以省略的,這就是你看的的:xxx=>xxx,xxx=>xxx或xxx:xxx,xxx:xxx,他們其實(shí)是{:xxx=>xxx,... }
:price是他的一個(gè)參數(shù)而已。
所以就出現(xiàn)了
f.label :name, class: "right inline"
這樣的程式碼, 他的意思是,
f.label (:name, {:class => "right inline"})
這樣,他就會(huì)創(chuàng)造一個(gè)label在form f下面,name是:name,而html標(biāo)籤中的class是"right inline"。
create_table :books do |t|
do|x|...end沒(méi)有什麼特殊的意義和{|x|}一樣,只是代表一個(gè)block而已, 這個(gè)程式碼中是有迭代出現(xiàn)的,他其實(shí)是類似:
File.open("xxx","xxx") do |f|
f.write(...)
end
的,當(dāng)然這樣也是合法的:
File.open("xxx","xxx") { |f|
f.write(...)
}
然後因?yàn)槔ㄌ?hào)可以省略就變成上面的樣子了。
對(duì)於ruby來(lái)說(shuō)要實(shí)現(xiàn)這樣的功能,只需要:
class Somethings
#...
def create_table(name)
# 為創(chuàng)建這個(gè)表做一些準(zhǔn)備……
# ...
yield @table
# 創(chuàng)建這個(gè)表
# ...
end
end
關(guān)於迭代器更具體的用法可以看看這個(gè):http://blog.csdn.net/classwang/article/details/4692856