Method definition begins with brackets, cannot understand its usefulness

In Ruby, I see a method definition as follows:

def [](param) # do stuff end 

What does the declaration of this method mean? How it works? When to use it? And how to call this type of method with an instance of an object?

+6
source share
3 answers

This is the name of the method, [] . Perhaps you already know Array#[] or Hash#[] . In your classes, you can also define such a method. What he will do is up to you.

 class Foo def [](param) # body end end f = Foo.new f[:some_value] 
+8
source

This means that the method is called " [] ". You call it like any other method:

 a = ['foo', 'bar', 'baz'] a.[](1) # => 'bar' 

In addition, for methods with this name, you can also call them as

 a[1] # => 'bar' 
+2
source

Have you read this Array # [] ? This will give you some idea about this.

  [1,2].[](1) # => 2 | | ---------> <--------- method name argument 
0
source

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


All Articles