Skip to content

Instantly share code, notes, and snippets.

@duckinator
Created May 25, 2016 08:08
Show Gist options
  • Save duckinator/ad75c0981d0a8c7197686f65a39cc36d to your computer and use it in GitHub Desktop.
Save duckinator/ad75c0981d0a8c7197686f65a39cc36d to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Module
def _refine(klass, &block)
raise TypeError, "wrong argument type #{klass.class} (expected Class)" unless klass.is_a?(Class)
const_set(klass.name, Class.new(klass, &block))
end
end
module StringFormat
#_refine String do
# Equivalent to:
class String < ::String
# "{foo} {1} {0}".format('bar', 'baz', foo: 'foo') #=> "foo baz bar"
def format(*args, **hsh)
self.clone.gsub(/{(\S+)}/) do
hsh[$1] || hsh[$1.to_sym] || args[$1.to_i]
end
end
end
end
raise String.new("[1] String responds to format().") if String.new("").respond_to?(:format)
module InsertRandomlyGeneratedModuleNameHere
include StringFormat
raise String.new("[2] String does not respond to format().") unless String.new("").respond_to?(:format)
puts String.new("{foo} {1} {0}").format('bar', 'baz', foo: 'foo') #=> "foo baz bar"
end
raise String.new("[3] String responds to format().") if String.new("").respond_to?(:format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment