Skip to content

Instantly share code, notes, and snippets.

@usergenic
Created October 27, 2010 21:52
Show Gist options
  • Select an option

  • Save usergenic/650089 to your computer and use it in GitHub Desktop.

Select an option

Save usergenic/650089 to your computer and use it in GitHub Desktop.
Ruby Proc Coercion for Fun and Profit
# 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