Search Results

Search found 3 results on 1 pages for 'eigenclass'.

Page 1/1 | 1 

  • General question about Ruby Eigenclass/Singleton

    - by Dex
    module MyModule def my_method; 'hello'; end end class MyClass class << self include MyModule end end MyClass.my_method # => "hello I'm unsure why "include MyModule" needs to be in the eigenclass in order to be called using just MyClass. Why can't I go: X = MyClass.new X.my_method How is this type of pattern useful if I can't call it from an instance?

    Read the article

  • Why isn't the eigenclass equivalent to self.class, when it looks so similar?

    - by The Wicked Flea
    I've missed the memo somewhere, and I hope you'll explain this to me. Why is the eigenclass of an object different from self.class? class Foo def initialize(symbol) eigenclass = class << self self end eigenclass.class_eval do attr_accessor symbol end end end My train of logic that equates the eigenclass with class.self is rather simple: class << self is a way of declaring class methods, rather than instance methods. It's a shortcut to def Foo.bar. So within the reference to the class object, returning self should be identical to self.class. This is because class << self would set self to Foo.class for definition of class methods/attributes. Am I just confused? Or, is this a sneaky trick of Ruby meta-programming?

    Read the article

  • Ruby: how does constant-lookup work in instance_eval/class_eval?

    - by Alan O'Donnell
    I'm working my way through Pickaxe 1.9, and I'm a bit confused by constant-lookup in instance/class_eval blocks. I'm using 1.9.2. It seems that Ruby handles constant-lookup in *_eval blocks the same way it does method-lookup: look for a definition in receiver.singleton_class (plus mixins); then in receiver.singleton_class.superclass (plus mixins); then continue up the eigenchain until you get to #<Class:BasicObject>; whose superclass is Class; and then up the rest of the ancestor chain (including Object, which stores all the constants you define at the top-level), checking for mixins along the way Is this correct? The Pickaxe discussion is a bit terse. Some examples: class Foo CONST = 'Foo::CONST' class << self CONST = 'EigenFoo::CONST' end end Foo.instance_eval { CONST } # => 'EigenFoo::CONST' Foo.class_eval { CONST } # => 'EigenFoo::CONST', not 'Foo::CONST'! Foo.new.instance_eval { CONST } # => 'Foo::CONST' In the class_eval example, Foo-the-class isn't a stop along Foo-the-object's ancestor chain! And an example with mixins: module M CONST = "M::CONST" end module N CONST = "N::CONST" end class A include M extend N end A.instance_eval { CONST } # => "N::CONST", because N is mixed into A's eigenclass A.class_eval { CONST } # => "N::CONST", ditto A.new.instance_eval { CONST } # => "M::CONST", because A.new.class, A, mixes in M

    Read the article

1