After last week, I know you've been eagerly waiting for this, the fifth article in my Ruby on Rails series. This one will give you an in-depth look at Loops, Methods, and Blocks. Well maybe Blocks. You'll have to see. So without a bunch of unnecessary yammering, let's get to it.
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”