【问题标题】:What do 'self' and 'new' mean in Ruby from Java perspective?从 Java 的角度来看,Ruby 中的“self”和“new”是什么意思?
【发布时间】:2012-01-05 03:39:41
【问题描述】:

我正在查看一些开源代码,无法理解这个 sn-p。

class Something
    def self.smart
       new.smart
    end

    def smart 
      "test"
    end
end

class Other < Something

println Other.smart

代码是否在每次调用smart 时都尝试实例化一个新实例?

【问题讨论】:

    标签: java ruby oop


    【解决方案1】:
    def self.smart
           new.smart
    end
    

    相当于static方法,可以通过类名访问。

    ... static ... smart()
    

    def smart 
          "test"
    end
    

    相当于instance方法,需要对象才能访问

    ... smart()
    

    new和java中的一样,创建了一个类的实例。

    而且整个事情是等价的。

    public static .... smart(){
       new ClassName().smart();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2012-12-18
      • 2011-05-11
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多