Skip to content

Instantly share code, notes, and snippets.

@alexcoplan
Created June 29, 2012 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcoplan/3019575 to your computer and use it in GitHub Desktop.
Save alexcoplan/3019575 to your computer and use it in GitHub Desktop.
String#to_proc in Ruby
# String#to_proc
# this can be used to evaluate a string to a proc.
class String
def to_proc
eval "Proc.new do\n#{self}\nend"
end
end
# demo
'puts 2+2'.to_proc.call # => 4
my_proc = 'print "Ho! "'.to_proc
3.times &my_proc # => Ho! Ho! Ho!
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment