Ruby Ruby 里面对象的方法调用方式除了 obj.method 的形式,还有 obj::method 的形式?

maxchen · October 10, 2018 · Last by theblock24block replied at October 10, 2018 · 1046 hits

闲来翻翻 builder 这个 gem 的源码,发现有下面这一段:

module Builder
  if Object::const_defined?(:BasicObject)
    BlankSlate = ::BasicObject
  else
    require 'blankslate'
    BlankSlate = ::BlankSlate
  end
end

里面有这个一个表达式:

Object::const_defined?(:BasicObject)

就在猜想,Ruby 里把消息发送给对象,除了用 . 等方式外,还有种方式是通过 :: 发送吗?

就在 irb 里试了,发现的确如此,不管是实例对象还是类对象,都可以,想跟大家确认下是这样的吗?

应该是,不过很少那样写,用 . 就可以了

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.
Remember: in Ruby, classes and methods may be considered constants too.

这篇文章可以看看
https://cbabhusal.wordpress.com/2015/03/26/ruby-ruby-dot-and-double-colon-operators/

nokogiri 就这样

You need to Sign in before reply, if you don't have an account, please Sign up first.