Thursday, January 20, 2011

What is Subroutines in Ruby??

Subroutines
A subroutine starts with def and ends with a corresponding end. Subroutines pass back values with the return keyword. In a welcome change from Perl, variables declared inside a subroutine are local by default, as shown by this program:
#!/usr/bin/ruby
def passback
howIfeel="good"
return howIfeel
end

howIfeel="excellent"
puts howIfeel
mystring = passback
puts howIfeel
puts mystring

In the preceding, note that the puts command writes the string and then prints a newline, as opposed to the print command, which doesn't print a newline unless you add a newline to the string being printed.

If the howIfeel variable inside subroutine passback were global, then after running the subroutine, the howIfeel variable in the main program would change from "excellent" to good. However, when you run the program you get this:
[slitt@mydesk slitt]$ ./hello.rb
excellent
excellent
good
[slitt@mydesk slitt]$

The first and second printing of the howIfeel variable in the main program both print as "excellent", while the value passed back from the subroutine, and stored in variable mystring prints as "good", as we'd expect. Ruby's variables are local by default -- a huge encapsulation benefit.

You can pass variables into a subroutine as shown in the following code:
#!/usr/bin/ruby
def mult(multiplicand, multiplier)
multiplicand = multiplicand * multiplier
return multiplicand
end

num1 = 4
num2 = 5
result = mult(num1, num2)
print "num1 is ", num1, "\n"
print "num2 is ", num2, "\n"
print "result is ", result, "\n"
[slitt@mydesk slitt]$ ./hello.rb
num1 is 4
num2 is 5
result is 20
[slitt@mydesk slitt]$

The value of num1 was not changed by running mult(), showing that arguments are passed by value, not reference, at least for integers. But what about for objects like strings?
#!/usr/bin/ruby
def concat(firststring, secondstring)
firststring = firststring + secondstring
return firststring
end

string1 = "Steve"
string2 = "Litt"
result = concat(string1, string2)
print "string1 is ", string1, "\n"
print "string2 is ", string2, "\n"
print "result is ", result, "\n"
[slitt@mydesk slitt]$ ./hello.rb
string1 is Steve
string2 is Litt
result is SteveLitt
[slitt@mydesk slitt]$

Once again, manipulations of an argument inside the subroutine do not change the value of the variable passed as an argument. The string was passed by value, not reference.

No comments:

Post a Comment