Wednesday, October 12, 2011

Defining functions in ruby

Defining functions in ruby is quite easy:

def sayHello
puts "Hello world"
end

Calling the function:
sayHello()

Output: Hello world
The first line of the function defines the function called sayHello. The next line is the body of the method, the same line we saw earlier: puts "Hello World". Finally, the last line end tells Ruby we’re done defining the method. Ruby’s response => nil tells us that it knows we’re done defining the method.

Taking the arguments in functions:
def sayName(name)
puts "Hello #{name}"
end

Calling the function:
sayName("k2")

Output : Hello k2
(Note how name is printed with #{} in "" via puts)
Defining the function with default arguments:
def sayDefault(name = "Wolf")
puts "Hello #{name.capitalize}"
end

Calling the function:
sayDefault()

Output: Hello World

Calling with arguments:
sayDefault("k2")



No comments:

Post a Comment