class vs Class.new, module vs Module.new

前端 未结 2 510
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 19:07

What is difference between class and Class.new & module and Module.new?

I know that:

  1. C

相关标签:
2条回答
  • 2020-12-11 19:39

    Class.new returns an object. class A returns nil. Same goes for modules.

    That's wrong. A class/module definition returns the value of the last expression evaluated inside of the class/module body:

    class Foo
      42
    end
    # => 42
    

    Typically, the last expression evaluated inside of a class/module body will be a method definition expression, which in current versions of Ruby returns a Symbol denoting the name of the method:

    class Foo
      def bar; end
    end
    # => :bar
    

    In older versions of Ruby, the return value of a method definition expression was implementation-defined. Rubinius returned a CompiledMethod object for the method in question, whereas YARV and most others simply returned nil.

    0 讨论(0)
  • 2020-12-11 19:42

    The interesting point that you missed between class keyword and Class::new is - Class::new accepts block. So when you will be creating a class object using Class::new you can also access to the surrounding variables. Because block is closure. But this is not possible, when you will be creating a class using the keyword class. Because class creates a brand new scope which has no knowledge about the outside world. Let me give you some examples.

    Here I am creating a class using keyword class :

    count = 2
    
    class Foo
        puts count
    end
    # undefined local variable or method `count' for Foo:Class (NameError)
    

    Here one using Class.new :

    count = 2
    Foo = Class.new do |c|
        puts count
    end
    # >> 2
    

    The same difference goes with keyword module and Module::new.

    0 讨论(0)
提交回复
热议问题