Organizing your code in methods
When writing applications, code needs to be structured in such a way that it can be reused, documented, and tested. The base of this structure is creating methods. In the next chapter, we will expand to object-oriented programming with classes and modules. A method has a name, can receive parameters, and always returns a value (nil
is also a value). See this, for example:
def leap_year?(year) divides_by_4 = (year % 4 == 0) divides_by_100 = (year % 100 == 0) divides_by_400 = (year % 400 == 0) divides_by_4 && !(divides_by_100 && !divides_by_400) end puts leap_year? 1900 # => false puts leap_year? 2000 # => true puts leap_year? 2020 # => true
Method definitions start with the def
keyword followed by the method name. In this case, the method name is leap_year?
, including the interrogation symbol. Then, if the method has parameters, they will come between parentheses. A method...