Methods provide a way to gather code (statements and expressions) into one place so that you can use it conveniently and, if necessary, repeatedly. You can define methods to do all kinds of things. In fact, most of the math operators in Ruby are actually methods.
This is the most concentrated discussion on methods that you'll find in this book, so you may find yourself coming back to this section after you have read further.
Here is a simple definition for a method named
created with the keywords
defhello puts "Hello, Matz!"
endhello # => Hello, Matz!
hello method simply outputs a string with
puts. On the flip side, you can undefine a method with
undefhello # undefines the method named hello hello # try calling this method now NameError: undefined local variable or method 'hello' for main:Object from (irb):11 from :0
You can also define methods that have arguments, as shown here in the
def repeat( word, times ) puts word * times end repeat("Hello! ", 3) # => Hello! Hello! Hello! repeat "Good-bye! ", 4 # => Good-bye! Good-bye! Good-bye! Good-bye!
repeat method has two arguments,
times. You can call
a method that has arguments with or without parentheses around the arguments. You can even
define method arguments without parentheses, but I don't usually do it that way.
Because you don't have to use parentheses, it is possible to have normal-looking math
equations when you use operator methods, such as
+. Each line that ...