frafferz/geek

# This is a comment

Ruby Utils

The #to_proc method is pretty useful - it allows all sorts of niceness, such as

1
[11,12,13].map(&:to_s) #=> ["11","12","13"]`

This works by calling Symbol#to_proc, which is defined something like:

1
2
3
def to_proc
  lambda { |object| object.send(self) }
end

But what about if you want to pass arguments to the function? Suppose you wanted to call #to_s(16) on each element in the array?

If you still want the compact formulation, you can add a [] method to the Symbol:

1
2
3
4
5
class Symbol
  def [](*args)
    lambda { |o| o.send(self, *args) }
  end
end

which means that you can use stuff like this:

1
2
[11,12,13].map(&:to_s[16]) #=> ["b","c","d"]`
[11,12,13].map(&:*[2]) #=> [22, 24, 26]