Ruby Index Method

Does Ruby have a concept of an indexer method, for example, in C #?

+3
source share
1 answer

Yes, a method named []takes one 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 the value in the index, name the method []=.

+10
source

Source: https://habr.com/ru/post/1781823/


All Articles