How to pass a function instead of a block [duplicate]

According to “Passing Methods like Blocks in Ruby”, you can pass a method as a block like so:

p [1,2,3].map(&method(:inc))

Don’t know if that’s much better than rolling your own block, honestly.

If your method is defined on the class of the objects you’re using, you could do this:

# Adding inc to the Integer class in order to relate to the original post.
class Integer
  def inc
    self + 1
  end
end

p [1,2,3].map(&:inc)

In that case, Ruby will interpret the symbol as an instance method name and attempt to call the method on that object.


The reason you can pass a function name as a first-class object in Python, but not in Ruby, is because Ruby allows you to call a method with zero arguments without parentheses. Python’s grammar, since it requires the parentheses, prevents any possible ambiguity between passing in a function name and calling a function with no arguments.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)