In Ruby, I see a method's definition like this:
def [](param)
# do stuff
end
What does this method declaration mean? How does it work? When to use it? And how to call this kinds of method with an instance object?
new ) the method new in Class is called; it calls allocate to allocate space for the new object, then it calls the initialize method of the object that's been allocated, passing it the arguments of the call to new (if any).
The only two required elements of a method declaration are the method name and the data type returned by the method. For example, the following declares a method named isEmpty() in the Stack class that returns a boolean value ( true or false ): class Stack { . . . boolean isEmpty() { . . . } }
The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place. It contains the instructions that implement the method.
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.
It's the method's name, []
. You might already know Array#[]
or Hash#[]
. In your classes you can define such method too. What it will do - it's up to you.
class Foo
def [](param)
# body
end
end
f = Foo.new
f[:some_value]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With