User defined functions in Ruby

Submitted by Karthikeyan on Sun, 21/10/2012 - 07:05

Example #1

Ruby Method that does not returns any argument

def rectarea(l,b)
  area = (l*b)
  puts area
end
rectarea(15,20)
Output

300

Example #2

Ruby Method that returns 2 arguments

def rectarea(l,b)
area = (l*b)
perimeter = 2*(l+b)
return area, perimeter
end
Area,Perimeter = rectarea(15,20)
puts Area, Perimeter
puts rectarea(15,20)
Output

300
70
300
70

Note : Ruby is case sensitive. 'Area' is not equal to 'area'.

Example #3

Ruby program that uses a block. test{..} The yield statement used in the method "test" invokes the code in the block "test" and the yield statement inside the "cal" function invokes the "cal" block. A block is always invoked from a function with the same name as that of the block.

def test
  puts "Welcome"
  yield
  puts "You are in the function"
  yield
  def cal
    yield
    puts "Addition value is #{@c}"
  end
  cal {puts "Enter value a :"
    @a=gets().to_i(10)
    puts "Enter b:"
    @b = gets().to_i(10)
    @[email protected][email protected]
  }
end
test{puts "You are in the block"}
Output

Welcome
You are in the block
You are in the function 
You are in the block
Enter value a :
5
Enter b:
7
Addition value is 12