加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ruby中,这种类型的定义是什么:self.class.method

发布时间:2020-12-17 02:35:13 所属栏目:百科 来源:网络整理
导读:我是一个尝试理解一些代码的NOOB. 这个self.class.current_section有什么作用? class MyClass class self def current_section(*section) if section.empty? @current_section else @current_section = section[0] end end end def current_section() self.
我是一个尝试理解一些代码的NOOB.

这个self.class.current_section有什么作用?

class MyClass
  class << self  
    def current_section(*section)
      if section.empty?
        @current_section
      else
        @current_section = section[0]
      end
    end
  end


  def current_section()
    self.class.current_section
  end

  def current_section=(section)
    self.class.current_section(section)
  end
end

解决方法

它将对象接收的消息(方法调用请求)转发到相应的类.

说你上课了

class MyClass
  def MyClass.current_section
    puts "I'm the class method."
  end

  def current_section
    self.class.current_section
  end
end

h = MyClass.new
h.current_section # outputs "I'm the class method."

调用h的方法,它查找h的类(MyClass)并调用该类的方法current_section.

因此,通过上面的定义,类MyClass的每个对象都有一个方法current_section,它被路由到类的中心current_section.

你问题中类方法的定义只是使用不同的语法来做同样的事情:向类对象添加一个方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读