Callables in block shorthand syntax
Given an object which does something silly like append “YAH” on to a string:
class Yahify
def self.call(str)
str + 'YAH'
end
end
How do we use this with the shorthand syntax for say map
or then
?
So instead of:
"foo".reverse.then { |str| Yahify.call(str) } # => "oofYAH
%w(one two three).map { |str| Yahify.call(str) } # => [oneYAH, twoYAH, threeYAH]
Note we could use Yahify.(str)
too as a shorthand for call
.
We want something like:
"foo".reverse.then(&Yahify) # => "oofYAH
%w(one two three).map(&Yahify) # => [oneYAH, twoYAH, threeYAH]
How &
works is explained in an earlier blog post.
The essence is that &
calls to_proc
on the given var, in the above case the Yahify
class. The returned proc is passed to
the method, e.g. map
. In the case of map
it will pass
each item in the collection in to the proc creating a new collection.
So we can add a to_proc
method:
class Yahify
def self.call(str)
str + 'YAH'
end
def self.to_proc
proc { |str| call(str) }
end
end
Yahify.to_proc.call("foo") # => "fooYAH"
We can then use our class as we wanted:
"foo".reverse.then(&Yahify) # => "oofYAH
%w(one two three).map(&Yahify) # => [oneYAH, twoYAH, threeYAH]