Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kisai
Created September 18, 2014 23:55
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 kisai/09d7dc5bb6aa5353a7d0 to your computer and use it in GitHub Desktop.
Save kisai/09d7dc5bb6aa5353a7d0 to your computer and use it in GitHub Desktop.
Define a singleton method for a ruby object
class A
class << self
def class_name
to_s
end
end
end
A.define_singleton_method(:who_am_i) do
"I am: #{class_name}"
end
A.who_am_i # ==> "I am: A"
guy = "Bob"
guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
guy.hello #=> "Bob: Hello there!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment