[Posted at
http://drnicwilliams.com/2006/09/28/new-magical-version-of-symbolto_proc/]
Before the magic, letâ??s go through a Beginnerâ??s Guide to Mapping, then
Advanced Guide to Symbol.to_proc, and THEN, the magical version. Its
worth it. Its sexy, nifty AND magical all at once.
- Beginnerâ??s Guide to Mapping
list = [â??1â?², â??2â?², â??3â?²]
=> ["1â?³, "2â?³, "3â?³]
list.map {|item| item.to_i}
=> [1, 2, 3]
Here we’re invoking to_i on each item of the list and returning the
result into a new list. That’s map/collect for you.
- Advanced Guide to Symbol.to_proc
After doing that a few times, you start wishing there was simpler
syntax. Enter: Symbol.to_proc
list.map &:to_i
=> [1, 2, 3]
It works. Just enjoy it. (see article for links on why it works)
- Magical version of Symbol.to_proc
Quite frankly, thatâ??s still a lot of syntax. Plus, I normally forget to
added parentheses around the &:to_i, and then latter I want to invoke
another method on the result, so I need to add the parentheses which is
a painâ?¦ anyway. I thought of something niftier and dare I say, more
magical.
How about this syntax:
list.to_is
=> [1, 2, 3]
By passing the plural version of a method, the array automagically
performs the above mapping on itself using the singular version of the
method.
Sexy! And here’s more examples:
(1…10).to_a.to_ss
=> [“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”]
(1…10).to_a.days
=> [86400, 172800, 259200, 345600, 432000, 518400, 604800, 691200,
777600, 864000]
[2,‘two’, :two].classes
=> [Fixnum, String, Symbol]
[2,‘two’, :two].classes.names
=> [“Fixnum”, “String”, “Symbol”]
[2,‘two’, :two].classes.names.lengths
=> [6, 6, 6]
So much happy syntax in one place!
I’ve got the library that gives you this syntax here:
http://drnicwilliams.com/2006/09/28/new-magical-version-of-symbolto_proc/
(at the bottom)
Nic