Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2011 16:58
What would you like to do?
Using s/string/string/ to replace things in strings… YAY RUBY!
class Proc
alias :/ :call
def s
optmap = {
"x" => Regexp::EXTENDED,
"i" => Regexp::IGNORECASE,
"m" => Regexp::MULTILINE
lambda do |find, replace, flags|
flags = flags.to_s
options = 0
flags.scan(Regexp.union(optmap.keys)) do |x|
options |= optmap[x]
find =, options)
meth = flags[/g/].to_s << "sub"
lambda { |string| string.public_send(meth, find, replace) }
# a variant of S that does not take flags
S = lambda { |find, replace| s[find, replace, ""] }.curry
puts (s/"Hello"/"hi"/:gi)["Hello hello world"]
puts (S/"Hello"/"hi")["Hello hello world"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment