Ruby Methods

Methods in Ruby

Methods are code blocks that contain a bunch of statements that are executed only when the method is called. Methods are the same as functions in the procedural and structured programming language. In object-oriented programming, language functions are called methods. Ruby is a purely object-oriented language, that’s why functions are called methods. In this chapter, we will learn how does work Ruby methods in detail.

Methods are very useful for reusing a block of code repeatedly without rewriting. It saves time and increases developer productivity.

Creating & Calling Ruby Methods

In Ruby, methods are very simple to define. Methods can be declared with the def keyword and a method end with the end keyword. Some languages use curly braces {..} for starting and ending blocks/methods/functions.

Non-parameterized methods

Curly braces are optional for non-parameterized methods, see the syntax and example program below:

Syntax
# creating methods without parameters
def method-name
    # statements go here
    # more statements
end
# calling the method
method-name
Example1
# creating method
def greet
    puts "Hello, World!"
end

#calling method
greet
Output
Hello, World!

Parameterized methods

You can also pass the unique values to a defined method each time you call the function. This can be happen using the method parameter. See the example below for clear understanding:

Syntax
def method-name(param1, param2, ...)
    # statements sit here
    # more statements
end
Example2
# creating method
def greet(name, birthdate)
    puts "Hey #{name}"
    puts "Your birth date is #{birthdate}"
end
#calling method
greet("Mohul", "28DEC")
Output
Hey Mohul
Your birthdate is 28DEC

Methods with the return statement

The return keyword returns a specific value from a method after a specific calculation or under a certain condition. Note that when a method is being executed and once the return keyword found the method is terminated by returning the value or sometimes no return value.

Syntax
def method-name(param1, param2, ...)
    # statements
    # more statements

    # doesn't return any value,
    # but method is stopped executing
    return

    # returns some value
    return returning_values
end
Example3
def sum(x, y)
    return x + y
end

result = sum(20, 35)

puts "Sum is #{result}"
Output
Sum is 55

Notes

  • Always method name should be started with the small case letter. Ins case of multiple words, capitalize the word from the second word. (ex: greet, myMethod, checkVal, myFirstMethod, etc).
  • Remember, in a method any statement after return keyword will not be executed. Because the return keyword stops the method from being executed and returns a value.
Posted in