DEV Community

Discussion on: Passing Functions as Arguments in Ruby

Collapse
citizen428 profile image
Michael Kohl • Edited

Note that the slightly more idiomatic approach is to pass in the method object as an argument:

receives_function(method(:first_option))
Enter fullscreen mode Exit fullscreen mode

This way receives_function can be blissfully ignorant as to what func is, as long as it responds to call (so we could also pass in a lambda).

You can even use default arguments:

def receives_function(func = method(:first_option))
  func.call
end
Enter fullscreen mode Exit fullscreen mode

This way there's a default argument and we can override it as needed. This can be quite useful at times, i.e. when you have a default behavior that you need most of the time (the method in the same scope), but occasionally want to override it (i.e. in a test).