简体   繁体   中英

How to access method defined in a module inside another module in Ruby?

Given the following example:

module A
  module B
    def whoa
      puts 'Whoa!'
    end
  end
end

How can I access the whoa method?

1.9.3p392 :047 > A.B.whoa
NoMethodError: undefined method `B' for A:Module

1.9.3p392 :048 > A::B.whoa
NoMethodError: undefined method `whoa' for A::B:Module

1.9.3p392 :049 > A::B::whoa
NoMethodError: undefined method `whoa' for A::B:Module

None of these approaches seems to work.

Assuming you don't want class level methods, you can also include the module into a class, instantiate an object of that class and call whoa :

class C
   include A::B
end

c = C.new
c.whoa
# Whoa!

You've define the method as an instance method. If you want to use the method without an instance, it should be a class method on the module:

module A
  module B
    def self.whoa
      puts 'Whoa!'
    end
  end
end

1.9.3p327 :009 > A::B.whoa
Whoa!
 => nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM