It's user error.

Debu.gs


Symbol#to_proc

I’ve never seen anyone use this, only recently read about it when I came across a blog.  It’s part of
Ruby/Extensions,
which has

some useful method definitions
,
as well as a few

cool but possibly evil

ones. The reason

Symbol#to_proc

is worth noting, though, is that it saves quite a bit of typing/punctuation for common tasks.
I think the examples from their docs sum up what it does the best:

%{john terry fiona}.map(&amp;:capitalize)&nbsp;&nbsp; # -&gt; %{John Terry Fiona}<br/>
sum = numbers.inject(&amp;:+)<br/>

The explanation is pretty simple: when you pass an object as a block, #to_proc is called on the object, just like the way #to_str is called when you try to concatenate a string with something, in order to coerce the object into the class you need. So if you were to do something like this:

class Symbol
  def to_proc
    proc { |obj, *args| obj.send(self, *args) }
  end
end

Then you’d have exactly what’s described above, a clean way to use coercion to your advantage. On the other hand, if you’re feeling a little perverse, and want to abuse your newfound knowledge, you can even define it for strings:

class String
  def to_proc
    eval "proc { |obj, *args| obj.send(#{self}, *args) }"
  end
end
[1, 2, 3].send(&':+, 4') # => [5, 6, 7]

See Also:

Tags: ruby


<< Previous: "You can't spell 'function pointers' without 'fun'"
Next: "Re-implementing Gloves" >>