class vs Class.new, module vs Module.new

前端 未结 2 516
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题