methods Ruby

Estimated reading time: 1 minute

methods

methods is a function . it start with def keyword.

def method_name(parameters)

end
  • demo 1
def method_name
  ## method body goes here
end
  • demo 2 / parameter
def method_name(msg)
  puts msg
end
  • demo 3 / multiple parameters
def method_name(msg, body)
  puts "This is " + msg + "body is here" + body
end

default parameter

def add_three(number,age=21)
  return number + age
end

returned_value = add_three(4)
puts returned_value
# 25

rest parameter

def add_three(number,*num)
  return  num
end

returned_value = add_three(4,5,5)
puts returned_value
# 5 5

return

def add_three(number)
  return number + 3
end

returned_value = add_three(4)
puts returned_value

source

ruby