I’ve been looking at some ruby code and noticed that some people treat methods like variables or constants.
class Test
def welcome_message
"Hello World"
end
def greet_user
p welcome_message
end
end
And then you might write a new class that inherits from this Test class, but change how it behaves.
class New_Test < Test
# changing the welcome message
def welcome_message
"Greetings"
end
end
When is it an appropriate time to do something like this? It appears to allow you to write more flexible code since I can perform more complex computations before returning a value, but I can’t come up with a way to justify writing a piece of code like the two Test classes above.
Why It Works
In Ruby, every method returns a value. In your given example of
p welcome_messageyou are asking Ruby to print the string representation of the return value of #welcome_message. (Technically it’s writing object.inspect to standard output, but it amounts to the same thing here.)If “Hello World” were something other object than a String, the result would still be similar. For example, if #welcome_method returned a Fixnum instead of a String, it would still appear to be printing a string.
Return Values
You could store your message in a class or instance variable, or use getter or setter methods on an object. However, sometimes it’s simply more convenient to use a return value directly in an expression rather than using a variable for intermediate storage.
Instead of storing and then dereferencing a variable like this:
you can just use the return value from #welcome_message directly.
This is unlikely to matter much in a contrived example like the one in the original question, but it may save time, effort, or memory in larger applications. Even if not, intermediate variables can be a source of bugs or programmer error, and it’s often just semantically clearer to use the values directly.
While this doesn’t apply to your limited example, it’s also a better practice to use an object’s public interface to request information. In such cases, methods that return values are essential.
Ruby is not an orthogonal language; there’s usually more than one valid way to do something. In the end, it’s about the semantics of what you’re trying to express in your code.