Methods in Ruby
A method is a group of statements written to perform a particular task.
Methods help us reuse the same code whenever required. Instead of writing the same code repeatedly, we can write it once inside a method and call it whenever needed.
Syntax:# Method definition
def method_name(arg1, arg2, ...)
statements
return stmt (optional)
end
# Method calling
method_name(arg1, arg2, ...)
Example 1: Method without arguments
# method definition
def msg
puts "Welcome to Ruby Programming"
end
# method calling
msg
Output:
ruby welcomemsg.rb
Welcome to Ruby Programming
Example 2: Method with arguments
# method definition
def addition(a, b)
result = a + b
puts "Sum = #{result}"
end
# method calling
addition(10, 20)
Output:
ruby addnums.rb
Sum = 30
Example 3: Method with return statement
# method definition
def addition(a, b)
return a + b
end
# method calling
result = addition(10, 20)
puts "Sum = #{result}"
Output:
ruby addnumsr.rb
Sum = 30