Skip to content

Instantly share code, notes, and snippets.

@jonaphin
Created June 29, 2011 01:59
Show Gist options
  • Save jonaphin/1052750 to your computer and use it in GitHub Desktop.
Save jonaphin/1052750 to your computer and use it in GitHub Desktop.
String#to_proc
### Jonathan Lancar - https://github.com/jonaphin ###
###################################
## String#to_proc Implementation ##
###################################
class String
# Evaluates a string as ruby code
def to_proc
proc { |arg| eval "#{arg}#{self}" }
end
end
p [1,2,3].map &' + 2 - 5'
# => [-2, -1, 0]
p (1..10).collect &" * 2"
# => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
## Reasoning ##
# A String as a proc, in my opinion, should try to evaluate itself
# It makes it easy and concise to evaluate ruby expressions consecutively
# The use case is fairly intuitive to developers, and seems like a "common use" scenario.
# Warning: The implementation above does not evaluate to the binding in which the string was written
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment