Skip to main content
Home
Live to Learn!

Main navigation

  • Home
  • Learn
    • FoxPro
    • MS-DOS
    • C PRG
    • Java
    • ASP
    • Ruby on Rails
    • ASP.NET
    • E-Books
    • Exam Preparation
    • Tools
  • Blog
  • Forums
  • Contact
User account menu
  • Log in

Breadcrumb

  1. Home
  2. Ruby and Rails

User defined functions in Ruby

Book navigation

  • Single line swapping in Ruby
  • Array Operations in Ruby
  • File operations in Ruby
  • User defined functions in Ruby
  • Classes and Objects in Ruby
  • Simple Form Hello Rails Application
  • Database Application using scaffold - [Video]
  • Session Management
  • Cookies Management in Ruby on Rails
  • File Uploads in Ruby on Rails
By Karthikeyan , 21 October, 2012

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)
    @c=@a+@b
  }
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
  • Add new comment

Comments

Featured Blog Posts

Convert Currency in Number to Words (Indian Rupees) - MS Excel
Foxpro Tutorial and Programs
Convert Currency in Number to Words in MS Word
Convert Currency in Number to Words (Indian Rupees) - Version 2
Best way to Use Rupee Symbol in Windows – Easy steps
Convert Currency in Number to Words - MS Access
Creating All in One Windows XP DVD with all Important Applications
RSS feed

© 2009-2025 Live to Learn.In

Terms of Use | Privacy Policy