Identity method factory in Ruby

Viewed 38

Is there a shortcut in Ruby to receive a lambda which simply returns its argument?

I'm trying to have the following function:

def some_method(x, y, decorator = ->(x) { x })
  …
end

Rewritten to look somehow like

def some_method(x, y, decorator = method(:itself))
  …
end

Maybe there's a way to change the receiver with Object#itself?

1 Answers

You have probably seen code like this plenty of times in ruby:

array.map(&:upcase)

Well, what does &:upcase actually mean? It's actually calling Symbol#to_proc.

Therefore, you could choose to define the method like this:

def some_method(x, y, decorator = :itself.to_proc)
  # ...
end
Related