我有一個骷髏級:紅寶石如何定義作家法「<<」
class Foo
def bar
# returns some sort of array
end
end
,但一個人如何能在「作家」的方法添加到「酒吧」,以便使陣列#推行爲?
Foo.new.bar<<['Smile']
_.bar #=> ['Smile']
編輯: 我應該進一步擴展我的問題。 有兩個類。 Foo和Bar,非常像ActiveRecord has_many關係,其中Foo has_many酒吧
但是我實際上將Bar的ID存儲在Foo的一個方法中。我的名字是方法bar_ids
所以@foo = Foo.new(:bar_ids => [1,2,3])
正如你可以想像,如果我想查什麼酒吧屬於@ FOO,我必須真正做類似Bar.where(:ID => @ foo.bar_ids)
所以我決定讓剛剛入選酒吧做到這一點 類Foo #另一種方法... 高清bar Bar.where(:id => bar_ids) end end
解決了。現在我可以做@ foo.bar#=>所有屬於@foo的酒吧
現在我也想擁有像ActiveRecord關聯那種推式方法,只是爲了在關聯另一個酒吧時刪除「id」鍵入反對Foo對象
目前,這個工程: @ foo.bar_ids < < Bar.new.id @ foo.save
但我想: @ foo.bar < < Bar.new#其中新酒吧的ID將被推入@foo的bar_ids方法 @ foo.save
感謝您的全力幫助,我非常感謝您對此的看法!
什麼是你究竟從杆法期待?它應該只作爲一個Array對象的getter? – David 2010-09-20 14:14:37
@大衛,這是完全正確的。我想要實現的就像ActiveRecord has_many關係,你可以做@ project.line_items << LineItem.create(...) – 2010-09-20 14:20:12
@Nik,'@project.line_items << ...'返回一個'Array',而不是'@ project'。 'Foo.new.bar'不可能返回一個可以同時調用''''和'Foo'對象的數組! – 2010-09-20 14:28:19