Ruby Loops - Reach Out and Touch Someone
(Page 4 of 5 )
Remember when that used to be AT&T's slogan? Probably not the brightest advice. Not to mention that if you could reach out and touch them, why would you call them? I mean they would literally be within an arm's reach of you.
Anyway, in this section we are going to learn how to create our own methods and call upon them to do our bidding. Muahhaha!
def own_you
puts “I PWN YOU!”
end
In the above example, we created a method named own_you. If we were to call it (and we will), it would print the sentence: I PWN YOU! to your computer screen. Let's go ahead and call it. No, not like that; put away your cell phone.
def own_you
puts “I PWN YOU!”
end
own_you
And there you have it; simple as can be. Note that the method will not run until you call it. Unlike my plethora of dogs, who won't come even when you do call them.
Arguing with Methods
Are methods really getting on your nerves? Go ahead, argue with them. Feel better? Well you shouldn't. All those methods ever did is whatever you asked.
In Ruby you can pass arguments to methods quite easily:
def insult(mama_joke)
puts mama_joke
end
insult “Yo mama so fat she wore an X-Men jacket and helicopters landed on her back”
This would result in the following print out:
“Yo mama so fat she wore an X-Men jacket and helicopters landed on her back”
You could also use the following method:
def bad_movie(first_name, second_name, third_name)
puts first_name + “ “ + second_name + “ “ + third_name
end
bad_movie “I”,“Heart”,”Huckabees.”
This would print out: I Heart Huckabees.
The “ “ in the puts line tells the program to add a space, while the + symbol concatenates the strings together.
Next: Scope >>
More Ruby-on-Rails Articles
More By James Payne