Writing your own methods
With def you define a method – a named piece of code you can call as often as you like:
def greeting(name)
"Hello, #{name}!"
end
greeting("Kaz")Small surprise: you've been calling methods since lesson 1 – because puts is one! Ruby makes the parentheses optional: puts "Hello" is really puts("Hello"). That works for your own methods too:
with_parens = greeting("Kaz")
without_parens = greeting "Kaz"
[with_parens, without_parens]That's exactly why so many Ruby lines read like plain language. The Rubyists' rule of thumb: omit the parentheses when the call reads like a statement (puts "…", require "csv") – use them when you keep computing with the result (greeting("Kaz").upcase). For calls with no arguments at all they're almost always omitted: name.upcase instead of name.upcase().
The value of a method's last line is automatically its return value – an explicit return is usually unnecessary. Very Ruby.
A method may have several parameters, and parameters may get a default value: leave the argument out when calling, and Ruby takes the default:
def greet(name, word = "Hello")
"#{word}, #{name}!"
end
puts greet("Kaz")
puts greet("Kaz", "Howdy")Methods that answer a yes-or-no question end in ? in Ruby – like even? or include? – and return true or false. And return leaves a method early, for example when there is nothing to compute:
def full?(strips)
strips >= 3
end
def share_bacon(strips, people)
return "Nobody here!" if people == 0
"Everyone gets #{strips / people} strips."
end
puts full?(5)
puts share_bacon(12, 4)
puts share_bacon(12, 0)Now a typical stumbling block: a method is a little room of its own. It does not see variables from outside – what it needs, it gets as an argument. Run the cell:
food = "bacon"
def whats_cooking
"Today we have #{food}."
end
whats_cookingRuby reports a NameError: inside whats_cooking there is no food. The fix is a parameter – def whats_cooking(food), called as whats_cooking(food). The same holds the other way round: variables created inside a method stay inside. That's on purpose: this way a method cannot break anything that isn't its own.
square(number) that returns the number multiplied by itself. Test it: square(9) as the last line.# def square(number)
# ...
# end
# square(9)
greeting_for(name, hour): before 12 it returns Good morning, Kaz!, from 12 on Good afternoon, Kaz! and from 18 on Good evening, Kaz!. The hour gets the default value 12, so that greeting_for("Kaz") works too. Test it with greeting_for("Kaz", 9) as the last line.# def greeting_for(name, hour = 12)
# ...
# end
# greeting_for("Kaz", 9)