Created
January 2, 2022 16:56
-
-
Save joesus/587a8bff331afa693e220b3c0e78eb6f to your computer and use it in GitHub Desktop.
Assigning methods to variables and invoking them in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assuming we're in an irb terminal. | |
# Keep in mind: | |
# * The return value of assignment in Ruby is the thing you assigned. | |
# * Ruby includes syntactic sugar to invoke methods with no parentheses. So `puts` is equivalent to `puts()` | |
# So when we write `foo = puts`, we assign `foo` the return value of puts which is always nil. | |
# What we're actually saying (without the sugar) is: | |
# `foo = puts()` | |
foo = puts | |
# => nil | |
# When we compare here, we're actually just comparing nil to the return value of `puts()` which is also nil. | |
foo == puts | |
# => true | |
# To assign to the method we need to use `method(:puts)` which return the actual method, | |
# not the result of calling the method with no arguments. | |
foo = method(:puts) | |
# => #<Method: Object(Kernel)#puts> | |
# Now we can call it with `call` | |
foo.call("bar") | |
# bar | |
# => nil | |
# Also we can test that it's the right method in our unit tests. | |
foo == method(:puts) | |
# => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment