This post originated from an RSS feed registered with Ruby Buzz
by rodney ramdas.
Original Post: Symbol#to_proc ... thy fearful symmetry
Feed Title: pinupgeek.com
Feed URL: http://feeds.feedburner.com/pinupgeek
Feed Description: A personal take on Ruby and Rails
Recently I reported on Nobuhiro Imai’s
patch to ActiveSupport’s Symbol#to_proc.
In Ruby 1.9 a similar Symbol#to_proc will be added. But on Ruby-Talk a discussion about the
correctness of this method is happening right now (yes, we are live and direct).
Eliot Temple provides a cool test case. Let me summarize, first here’s the current ActiveSupport (i.e. Rails)
version:
irb(main):017:0> class Symbol
irb(main):018:1> def to_proc
irb(main):019:2> Proc.new { |obj, *args| obj.send(self, *args) }
irb(main):020:2> end
irb(main):021:1> end
This will fail when #reverse-ing arrays. Turns out this is about the same way it works in the upcoming Ruby 1.9
[4,5,6], [7,8,9]].map &:reverse
Which brings us back to Nobuhiro-san’s patch that does make reversing work. He provides the following examples. This is his definition:
class Symbol
def to_proc
Proc.new{|*args| args.shift.__send__(self, *args)}
end
end
I’m only starting to understand this stuff, just barely, so correct me if I’m wrong. I have an instinctive feel of what’s going on
but it’s hard to translate.
In the Rails version it looks like it’s assumed that Symbol#to_proc takes an array where it’s members are mapped as key, method pairs, hence *args.
You cannot reverse it since that would not make sense. In Noburio-san’s version to_proc takes anything it’s given ,doesn’t assume anything about it, and calls __send__ on itself. I need to try to make a graphical representation of this maybe
that will help me to understand it. (I think __send__is used rather then Object#send to avoid some sort of name clashing or something).
At this point my brain is in a Gordian Knot and I’m gasping for air, I need to study this a bit more. If you can help, please comment. I will wash your car or camper if you can make me understand this.
Finally , here the verse that prompted the title for this post, fearful indeed.
TIGER, tiger, burning bright
In the forests of the night,
What immortal hand or eye
Could frame thy fearful symmetry?
(by William Blake)