Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created May 7, 2023 00:46
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 packrat386/aa2fe24a739ce57a1cdca09479a2d14c to your computer and use it in GitHub Desktop.
Save packrat386/aa2fe24a739ce57a1cdca09479a2d14c to your computer and use it in GitHub Desktop.
#### these options use the eigenclass ####
## def on an identifier
my_object = Object.new
def my_object.foo
puts "foo"
end
my_object.foo
## define_singleton_method
my_object = Object.new
my_object.define_singleton_method(:foo) do
puts "foo"
end
my_object.foo
## def inside the eigenclass
my_object = Object.new
class << my_object
def foo
puts "foo"
end
end
my_object.foo
## define_method on the eigenclass
my_object = Object.new
class << my_object
define_method(:foo) do
puts "foo"
end
end
my_object.foo
## def inside a module we extend
my_module = Module.new do
def foo
puts "foo"
end
end
my_object = Object.new
my_object.extend(my_module)
my_object.foo
## define_method on a module we extend
my_module = Module.new
my_module.define_method(:foo) do
puts "foo"
end
my_object = Object.new
my_object.extend(my_module)
my_object.foo
#### these options use class ancestry ####
## def inside a class that we inherit from
my_class = Class.new do
def foo
puts "foo"
end
end
my_object = my_class.new
my_object.foo
## define_method on a class that we inherit from
my_class = Class.new
my_class.define_method(:foo) do
puts "foo"
end
my_object = my_class.new
my_object.foo
#### only `Module` has define_method ####
## can't define_method on an Object
my_object = Object.new
begin
my_object.define_method(:foo) do
puts "foo"
end
rescue => e
puts "can't defined_method on an Object: #{e.message}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment