Ruby – Methods

Methods provide a way to collect and organize programs statements and expressions into one place so that you can use them in an easy way and repeatedly when you want. The majority of Ruby’s operators are Methods.

Here is an example of a definition of a method name hello

def hello
 puts "Hellow, world!"

When you invoke the method hello, it outputs or emits a string:

hello # => Hello, World!

You can undefine a method with undef:

undef hello # undefines the metho name hello
hello # try calling this method now
NameError: undefined local variable or method
 'hello' for main:Object

Methods might or might not have parameters. The repeat method, inane as it is, takes parameters, word and times:

def repeat( word, times)
 puts word * times

repeat("Hello!, 3) $ => Hellow! Hello! Hello!
repeat "Goodbye!", 4 => Goodbye! Goodbye!
 Goodbye! Goodbye!

Parentheses are optional in most method definitions and calls.

  • If you call a method within a method-a a nested call it might cause some confusion
  • When using parentheses, remember that opening parenthesis must follow the method name with no intervening space.

Also published on Medium.