2007/11/28

String#to_proc

Raganwald is one of my favorite bloggers. Every entry he writes inspires me and makes me think. A while ago he ported String#to_proc from Oliver Steele's functional javascript library to ruby. You have to read his entry for yourself but one thing that caught my eye was his definition of the factorial function using String#to_proc:


factorial = "(1.._).inject &'*'".to_proc
factorial[5] # -> 120


I don't know about you, but I think implementations like this are showing us whats possible in this language.

Never stop writing raganwald! Thanks.

2 comments:

Reginald Braithwaite said...

Thanks for the nice words! If you are using Rails or Ruby 1.9, you can also do the factorial thing using String#to_proc and Symbol#to_proc:

factorial = "1.._".inject(&:*).to_proc

Have fun!

Christoph Hilty said...

Yeah thanks, I like this version even more. Until now I do most of my ruby/rails work in my spare time but I have gladly noted that your work has been integrated into the class Symbol with Ruby 1.9. That’s why I like this community. Thanks a lot for your comment!