开发者

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 &开发者_Go百科lt;< 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]


Return an object that has the << method defined.


Unless I'm misunderstanding what you're wanting, why not just make the bar method a getter for an internal array member?

class Foo
  attr_reader :bar

  def initialize
    @bar = []
  end
end

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜