Home » Ruby Methods

Ruby Methods

Ruby methods prevent us from writing the same code in a program again and again. It is a set of expression that returns a value.

Ruby methods are similar to the functions in other lnguages. They unite one or more repeatable statements into one single bundle.


Defining Method

To use a method, we need to first define it. Ruby method is defined with the def keyword followed by method name. At the end we need to use end keyword to denote that method has been defined.

Methods name should always start with a lowercase letter. Otherwise, it may be misunderstood as a constant.

Syntax:

Example:

Ruby method 1

Here, we have defined a method welcome using def keyword. The last line end keyword says that we are done with the method defining.

Now let’s call this method. A method is called by just writing its name.

Ruby method 2


Defining Method with Parameter

To call a particular person, we can define a method with parameter.

Ruby method 3

Here, #{name} is a way in Ruby to insert something into string. The bit inside the braces is turned into a string.

Let’s call the method by passing a parameter Edward.

Ruby method 4


Next TopicRuby blocks

You may also like