The Basic Structure of the Ruby Method
As we have seen, the basic structure of a method is as follows:
def echo(var) puts var end
We are defining a method named echo
that accepts the var
variable as a parameter or argument. The end
keyword marks the end of the block of code. The code between the def
and end
statements is known as the method body or the method implementation.
Methods are always called on an object. In Ruby, a method is called a message, and the object is called the receiver. The online Ruby documentation uses this language specifically, so it is good to get used to this vocabulary.
In the previous example, however, it doesn't seem like there is an object. Let's investigate this through IRB:
def echo(var) puts var end => :echo echo "helloooo!" helloooo! => nil self => main self.class => Object
Here, we've defined and called our echo
method in IRB. We use the self
keyword, which is a reference...