Skip to content

Instantly share code, notes, and snippets.

@martinx
Forked from emrekutlu/add_instance_methods.rb
Last active August 29, 2015 14:13
Show Gist options
  • Save martinx/036816d66900f4552646 to your computer and use it in GitHub Desktop.
Save martinx/036816d66900f4552646 to your computer and use it in GitHub Desktop.
class Message
[:hello, :goodbye].each do |method_name|
define_method method_name do |arg|
"#{method_name} #{arg}"
end
end
end
#irb
Message.instance_methods false #=> [:hello, :goodbye]
Message.new.hello 'emre' #=> "hello emre"
Message.new.goodbye 'emre' #=> "goodbye emre"
class Message
def create_instance_methods *methods
methods.each do |method_name|
self.class.send :define_method, method_name do |arg|
"#{method_name} #{arg}"
end
end
end
end
#irb
Message.instance_methods false #=> [:create_instance_methods]
Message.new.create_instance_methods 'fork' #=> ["fork"]
Message.instance_methods false #=> [:create_instance_methods, :fork]
Message.new.fork 'emre' #=> "fork emre"
class Message
def self.create_instance_methods *methods
methods.each do |method_name|
define_method method_name do |arg|
"#{method_name} #{arg}"
end
end
end
end
#irb
Message.singleton_methods #=> [:create_instance_methods]
Message.create_instance_methods 'follow' #=> ["follow"]
Message.instance_methods false #=> [:follow]
Message.new.follow 'emre' #=> "follow emre"
class Message
def create_singleton_methods *methods
methods.each do |method_name|
self.class.singleton_class.send :define_method, method_name do |arg|
"#{method_name} #{arg}"
end
end
end
end
#irb
Message.instance_methods false #=> [:create_singleton_methods]
Message.new.create_singleton_methods 'poke' #=> ["poke"]
Message.singleton_methods false #=> [:poke]
Message.poke 'emre' #=> "poke emre"
class Message
def self.create_singleton_methods *methods
methods.each do |method_name|
singleton_class.send :define_method, method_name do |arg|
"#{method_name} #{arg}"
end
end
end
end
#irb
Message.singleton_methods false #=> [:create_singleton_methods]
Message.create_singleton_methods 'like' #=> ["like"]
Message.singleton_methods false #=> [:create_singleton_methods, :like]
Message.like 'emre' #=> "like emre"
#ruby 1.9.2
class Message
end
#irb
Message.singleton_class #=> #<Class:Message>
#ruby 1.8.x
class Message
#define this method to get singleton class
def self.singleton_class
class << self
self
end
end
end
#irb
Message.singleton_class #=> #<Class:Message>
$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment