What if we want to say “Hello” a lot without getting our fingers all
tired? We need to define a method!
The code def h
starts the definition of the method. It tells Ruby that we’re
defining a method, that its name is h
. 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.
Now let’s try running that method a few times:
irb(main):013:0> h Hello World! => nil irb(main):014:0> h() Hello World! => nilWell, that was easy. Calling a method in Ruby is as easy as just
mentioning its name to Ruby. If the method doesn’t take parameters that’s all you
need. You can add empty parentheses if you’d like, but they’re not
needed.
What if we want to say hello to one person, and not the whole world?
Just redefine h
to take a name as a parameter.
So it works… but let’s take a second to see what’s going on here.
What’s the #{name}
bit? That’s Ruby’s way of inserting something into
a string. The bit between the braces is turned into a string (if it
isn’t one already) and then substituted into the outer string at that
point. You can also use this to make sure that someone’s name is
properly capitalized:
A couple of other tricks to spot here. One is that we’re calling
the method without parentheses again. If it’s obvious what you’re
doing, the parentheses are optional. The other trick is the default
parameter World
. What this is saying is “If the name isn’t
supplied, use the default name of @”World"@".
What if we want a real greeter around, one that remembers your name and
welcomes you and treats you always with respect. You might want to use an
object for that. Let’s create a “Greeter” class.
The new keyword here is class
. This defines a new class called
Greeter and a bunch of methods for that class. Also notice @name
.
This is an instance variable, and is available to all the methods of
the class. As you can see it’s used by say_hi
and say_bye
.
So how do we get this Greeter class set in motion? Create an object.