2010-09-20 46 views
0

我有一個骷髏級:紅寶石如何定義作家法「<<」

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

感謝您的全力幫助,我非常感謝您對此的看法!

+0

什麼是你究竟從杆法期待?它應該只作爲一個Array對象的getter? – David 2010-09-20 14:14:37

+0

@大衛,這是完全正確的。我想要實現的就像ActiveRecord has_many關係,你可以做@ project.line_items << LineItem.create(...) – 2010-09-20 14:20:12

+0

@Nik,'@project.line_items << ...'返回一個'Array',而不是'@ project'。 'Foo.new.bar'不可能返回一個可以同時調用''''和'Foo'對象的數組! – 2010-09-20 14:28:19

回答

2
class Foo 
    attr_reader :bar 
    def initialize 
    @bar = Array.new 
    def @bar.<< arg 
     self.push arg.id 
    end 
    end 

end 

class Bar 
    attr_accessor :id 
    def initialize id 
    self.id = id 
    end 
end 


f = Foo.new 
bars = (1..5).map{|i| Bar.new i} 

f.bar << bars[2] 
f.bar << bars[4] 

p f.bar #=> [3, 5] 
+0

@Ormuriauga。這看起來很酷,你是否會友好地解釋爲什麼def @bar。<< arg是否在初始化? – 2010-09-20 15:12:03

+1

@Nik,是ormuriauga的解決方案非常酷。 'def @bar。<<'在'Foo'的'initialize'方法中,因爲他在那裏定製了'@ bar'('Array')對象(通過用單例方法覆蓋普通的數組''''方法)。 – horseyguy 2010-09-20 18:30:10

+0

@Ormuriauga&@Banister謝謝你。 – 2010-09-20 20:43:27

1

返回已定義方法<<的對象。

+0

因此,根據我的例子,bar/does /返回一個數組,它具有<<定義,所以我完成了? – 2010-09-20 14:13:52

+0

如果你總是返回相同的數組對象,那麼你就完成了。否則,'_.bar#=> ['Smile']'不起作用 – David 2010-09-20 14:18:52

0

除非我誤解了你的想法,爲什麼不把bar方法作爲內部數組成員的getter?

class Foo 
    attr_reader :bar 

    def initialize 
    @bar = [] 
    end 
end 

f = Foo.new 
f.bar << 'abc' 
# f.bar => ['abc']