Skip to content

Instantly share code, notes, and snippets.

@halferty
Last active June 23, 2016 23:41
Show Gist options
  • Save halferty/0990293932171c34eb4a6193bb095203 to your computer and use it in GitHub Desktop.
Save halferty/0990293932171c34eb4a6193bb095203 to your computer and use it in GitHub Desktop.
Ruby metaprogramming with singleton_class
[1] pry(main)> a = Object.new
=> #<Object:0x007f90fc8f40f0>
[2] pry(main)> a.singleton_class
=> #<Class:#<Object:0x007f90fc8f40f0>>
[3] pry(main)> a.singleton_class.send(:define_method, "asdf") { |a| "hi there " + a }
=> :asdf
[4] pry(main)> a.asdf
ArgumentError: wrong number of arguments (0 for 1)
from (pry):3:in `block in __pry__'
[5] pry(main)> a.asdf("gg")
=> "hi there gg"
[6] pry(main)> b = Object.new
=> #<Object:0x007f90fa981bc8>
[7] pry(main)> b.asdf("gg")
NoMethodError: undefined method `asdf' for #<Object:0x007f90fa981bc8>
from (pry):7:in `__pry__'
[1] pry(main)> a = "Hello"
=> "Hello"
[2] pry(main)> a.class.send(:define_method, "asdf") { "Hi there!" }
=> :asdf
[3] pry(main)> a.asdf
=> "Hi there!"
[4] pry(main)> b = "Hello again!"
=> "Hello again!"
[5] pry(main)> b.asdf
=> "Hi there!"
[6] pry(main)> a.singleton_class.send(:define_method, "fdsa") { "Hey there again!" }
=> :fdsa
[7] pry(main)> a.fdsa
=> "Hey there again!"
[8] pry(main)> b.fdsa
NoMethodError: undefined method `fdsa' for "Hello again!":String
from (pry):8:in `__pry__'
[9] pry(main)> a.singleton_class.send(:define_method, "aaaa") { |a, b| "And the result is: " + a.to_s + b.to_s }
=> :aaaa
[10] pry(main)> a.aaaa(1, 2)
=> "And the result is: 12"
[11] pry(main)> a.respond_to?(:aaaa)
=> true
[12] pry(main)> b.respond_to?(:aaaa)
=> false
[13] pry(main)> c = a.singleton_class.new
TypeError: can't create instance of singleton class
from (pry):13:in `new'
[14] pry(main)> Object.new.methods
=> [:pry,
:__binding__,
:pretty_print,
:pretty_print_cycle,
:pretty_print_instance_variables,
:pretty_print_inspect,
:nil?,
:===,
:=~,
:!~,
:eql?,
:hash,
:<=>,
:class,
:singleton_class,
:clone,
:dup,
:itself,
:taint,
:tainted?,
:untaint,
:untrust,
:untrusted?,
:trust,
:freeze,
:frozen?,
:to_s,
:inspect,
:methods,
:singleton_methods,
:protected_methods,
:private_methods,
:public_methods,
:instance_variables,
:instance_variable_get,
:instance_variable_set,
:instance_variable_defined?,
:remove_instance_variable,
:instance_of?,
:kind_of?,
:is_a?,
:tap,
:send,
:public_send,
:respond_to?,
:extend,
:display,
:method,
:public_method,
:singleton_method,
:define_singleton_method,
:object_id,
:to_enum,
:enum_for,
:gem,
:pretty_inspect,
:==,
:equal?,
:!,
:!=,
:instance_eval,
:instance_exec,
:__send__,
:__id__]
[15] pry(main)> a.singleton_methods
=> [:fdsa, :aaaa]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment