Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method definition begins with brackets, can't understand its usefulness

Tags:

ruby

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?

like image 382
medBouzid Avatar asked Sep 01 '13 20:09

medBouzid


People also ask

What does the new () method do when called for a particular class?

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).

How methods are declared in a class?

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() { . . . } }

What is method definition and declaration in Java?

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.

How do you define a method How do you invoke a 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.


1 Answers

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]
like image 151
Sergio Tulentsev Avatar answered Nov 14 '22 23:11

Sergio Tulentsev