Skip to content

Instantly share code, notes, and snippets.

@joesus
Created January 2, 2022 16:56
Show Gist options
  • Save joesus/587a8bff331afa693e220b3c0e78eb6f to your computer and use it in GitHub Desktop.
Save joesus/587a8bff331afa693e220b3c0e78eb6f to your computer and use it in GitHub Desktop.
Assigning methods to variables and invoking them in Ruby
# 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