Defining a Method
As we’ve seen, a method is defined using the keyword def.
The keyword def creates a method and returns the name of the method as a symbol, which, as we saw in Specifying Access Control, allows us to put decorator methods like private before the declaration.
The body of a method contains normal Ruby expressions. The return value of a method is the value of the last expression executed or the argument of an explicit return expression.
An important fact about def is that if you define a method a second time, Ruby won’t raise an error, it’ll print a warning, and then it’ll redefine the method using the second definition:
| class Batman |
| def who_is_robin |
| puts "Dick Grayson" |
| end |
| |
| def who_is_robin |
| puts ... |
Get Programming Ruby 3.3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.