Is there in Ruby the concept of indexer method such as in C#?
Asked
Active
Viewed 1,116 times
1 Answers
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