0

I learning ruby singletons and have misunderstanding with such code:

class MyClass
  def self.class_singleton_mymethod
  end
end

class_singleton = class << MyClass
  self
end

puts class_singleton.methods.grep(/mymethod/)  # => []


obj = MyClass.new

def obj.object_singleton_mymethod
end

object_singleton = class << obj
  self
end

puts object_singleton.methods.grep(/mymethod/) # => class_singleton_mymethod

Why class_singleton not contains class's Class method and object_singleton instead of Object's singleton method contains class's Class method?

2 Answers 2

2

I think you have the notion of methods and instance_methods mixed up. If you were to replace all instances of methods with instance_methods, you will see the results you expect.

instance_methods is used to enumerate which methods a class's instances have. methods is used to enumerate what methods the object has. (Class objects are objects too, and have their own methods like new that are not instance methods.

For example, String#slice is an instance method; you can call slice on string instances. On the other hand, String.new is a method on String itself; you don't call new on string instances, but you can call String.new (i.e., on the String class object itself) to create a new string.)

Sign up to request clarification or add additional context in comments.

1 Comment

@Vladimir: Thanks, it took me two tries to get it right, but I'm glad to have an answer I'm happy with. :-)
0

I'm not sure i understand, but are your trying to implement the Singleton Design Pattern?

Use the Singleton Module it implements the tern for you, you just include it

6 Comments

-1 No. Singleton classes in Ruby have nothing to do with the singleton pattern.
I try to understand why class_singleton (that contains Sinleton object for MyClass) not have MyClass singleton method inside
He's talking about singleton classes/eigenclasses in Ruby. The name is a bit confusing, but basically, every object has a unique singleton class right below its class in the class hierarchy.
Hey i waa trying to be helpful, I said i wasnt sure, was that really the need to downvote? I somewhat understand the difference between eigenclass and Singleton pattern, at least to the point they are different, although have little knowledge of the former. Just wasn't sure what was being asked. Thats why I prefaced my answer in such a way. The terminology can confusing, I thought that this might be helpful, apparently I was wrong, my apologies.
@loosecannon: Actually, I dislike (incorrect) speculative answers, and feel they have no place in an "experts' Q&A site", so I will downvote them when I see them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.