Created
October 27, 2010 21:52
-
-
Save usergenic/650089 to your computer and use it in GitHub Desktop.
Ruby Proc Coercion for Fun and Profit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Given this is the definition of Symbol#to_proc as was added | |
| # in ActiveSupport (and in the Ruby Extensions project before | |
| # that) and later added to core Ruby 1.9 in C... | |
| class Symbol | |
| def to_proc | |
| proc { |obj| obj.send(self) } | |
| end | |
| end | |
| # Such a device enables the following code... | |
| >> ['apple','banana','cabbage'].map(&:length) | |
| => [5, 6, 7] | |
| # ...as an alternative/analog to... | |
| >> ['apple','banana','cabbage'].map { |s| s.length } | |
| => [5, 6, 7] | |
| # What might be good use-cases for and definitions of #to_proc | |
| # for the following classes: Hash, Regexp and Class. | |
| # Please give implementation code of `def to_proc` for the | |
| # classes and usage examples to support your ideas. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment