From: Robert Klemme Date: 2008-07-27T23:59:46+09:00 Subject: Re: "nested" methods On 27.07.2008 16:02, Stefan Buhr wrote: > I want to do this: > > @myclass.items[5] = an_item > > But the items object of @myclass should have an custom setter. I have > tried this: > class Myclass > def items > def []= value > -code- > end > end > end > > but this does not work. Your nested method is defined for Myclass. Basically something like nested methods does not exist in Ruby. The only difference is the point in time when the nested method will be defined (after the other method has been executed): $ irb irb(main):001:0> class M irb(main):002:1> def x irb(main):003:2> def y; 9; end irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> m=M.new => # irb(main):007:0> m.y NoMethodError: undefined method `y' for # from (irb):7 irb(main):008:0> m.x => nil irb(main):009:0> m.y => 9 irb(main):010:0> m=M.new => # irb(main):011:0> m.y => 9 irb(main):012:0> > How can i do that? class Myclass def items @items ||= [] end end Now you have a member of type Array in Myclass and can use its method []=. You can as well do this class Myclass class Items def []= idx, val # whatever end end def items @items ||= Items.new end end Kind regards robert