Friday, September 16, 2011

Ruby- Defining a method

Let's start with an example
 
irb(main):001:0> def h
irb(main):002:1> puts "Ruby Language"
irb(main):003:1> end
=> nil

The definition of the method starts with keyword def and an identifier to the method (i.e., h). Next comes the actual body of the method and the keyword end as the delimiter.


Running a method

irb(main):004:0> h
Ruby Language
=> nil
irb(main):005:0> h()
Ruby Language
=> nil

Calling a method in Ruby is as easy as just mentioning its
name to Ruby. If the method does not take parameters that’s all you need. You can add empty parentheses if you would like, but they are not needed.



Parameterised method

Ruby provides facility to define methods that take arguments/parameters.

irb(main):006:0> def g(name)
irb(main):007:1> puts "Hello #{name}!"
irb(main):008:1> end
=> nil 
irb(main):009:0> g("Friend")
Hello Friend!
=> nil


Using default parameter

We can provide the default parameter, that should be used when the method is invoked without passing arguments, by equating the value to the parameter while defining the method.

irb(main):010:0> def g(name = "World")
irb(main):011:1> puts "Hello #{name.capitalize}!"
irb(main):012:1> end
=> nil 
irb(main):013:0> g("dhanoop")
Hello Dhanoop!
=> nil
irb(main):014:0> g
Hello World!
=> nil

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...