5

Is there in Ruby the concept of indexer method such as in C#?

mgamer
  • 13,580
  • 25
  • 87
  • 145

1 Answers1

11

Yes, a method named [] taking a single argument:

>> class Foo
>>  def [](idx)
>>   idx * 5
>>  end
>> end
=> nil
>> 
?> f = Foo.new
=> #<Foo:0x101098d80>
>> f[8]
=> 40
>> f[1]
=> 5

If you need to set a value at an index, name the method []=.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398