obj = SomeObject.new
def obj.new_method
\"do some things\"
end
puts obj.new_method
> \"do some things\"
This works ok. However, I need to do
class Some
end
obj = Some.new
class << obj
def hello
puts 'hello'
end
end
obj.hello
obj2 = Some.new
obj2.hello # error
Syntax class << obj
means that we are opening definition of the class for an object. As you probably know we can define Ruby class methods using syntax like this:
class Math
class << self
def cos(x)
...
end
def sin(x)
...
end
end
end
Then we can use those methods like this:
Math.cos(1)
In Ruby, everything is an object - even classes. self
here is an object of Math class
itself (you can access that object with Math.class
). So syntax class << self
means we are opening class for Math class object
. Yes, it means that Math class
has class too (Math.class.class).
You can use modules.
module ObjSingletonMethods
def new_method
"do some things"
end
end
obj.extend ObjSingletonMethods
puts obj.new_method # => do some things
Now if you need to add more methods to that object, you just need to implement the methods in the module and you are done.