ruby how to define writer method with "<<"

I have a skeleton class:

class Foo
   def bar
    # returns some sort of array
   end
end

but how can one add the 'writer' method to 'bar' so to enable the Array#push behavior?

Foo.new.bar<<['Smile']
_.bar #=> ['Smile']

EDITED: I should expand my question further. There are two classes. Foo, and Bar, much like the ActiveRecord has_many relation where Foo has_many Bars

But I am actually storing the ids of Bar inside a method of Foo. I name that method bar_ids

so @foo = Foo.new(:bar_ids => [1,2,3])

As you can imagine, if I ever want to look up what Bars belong to @foo, I have to actually do something like Bar.where(:id => @foo.bar_ids)

So I decided to make another method just named bar to do just that class Foo #... def bar Bar.where(:id => bar_ids) end end

That worked out. now I can do @foo.bar #=> all the bars belonging to @foo

Now I also want to have that kind of push method like ActiveRecord associations, just to cut out the "id" typing when associating another bar object to a foo object

Currently, this works: @foo.bar_ids << Bar.new.id @foo.save

But I want: @foo.bar << Bar.new #where the new bar's id will get pushed in the bar_ids method of @foo @foo.save

Thanks for all of your help, I really appreciate your thoughts on this!


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]

返回已定义<<方法的对象。


除非我误解你想要的东西,为什么不直接让bar方法成为内部数组成员的getter?

class Foo
  attr_reader :bar

  def initialize
    @bar = []
  end
end

f = Foo.new
f.bar << 'abc'
# f.bar => ['abc']
链接地址: http://www.djcxy.com/p/95428.html

上一篇: Ruby运算符方法调用与常规方法调用

下一篇: 红宝石如何用“<<”来定义写作者的方法