From: Pit Capitain Date: 2005-11-25T04:12:40+09:00 Subject: Re: syntax error when defining index setter []= jchris@gmail.com schrieb: > Thanks Yuri, > unfortunately my problems is not as simple. If all I needed was an > array I could write > > class T > attr_accessor :items > def initialize > @items = [] > end > end > > but what I need is something that acts like an array from outside of > the class, but handles transformations to and from a more complex data > structure "behind the scenes", ie: > > class List < ActiveRecord::Base > has_many :middlemen > > def items > middlemen.collect {|middleman| middleman.item} > end > > def items=(new_items) > new_middlemen = [] > new_items.each do |new_item| > new_middlemen << Middleman.create :item => new_item > end > middlemen = new_middlemen > end > > def items[]=(index, new_item) #### this line gives a syntax error > new_middleman = Middleman.create :item => new_item > middlemen[index] = new_middleman > end > > end If you really want to have the syntax list.items[5] = "new" you need to define the "[]=" method on the return value of the "items" method, for example (untested) def items result = middlemen.collect {|middleman| middleman.item} def result.[]=(index, new_item) new_middleman = Middleman.create :item => new_item middlemen[index] = new_middleman end end Regards, Pit