Ruby模块方法访问

new*_*_86 27 ruby

我有一个常量的ruby模块.它有一个变量列表和一个应用格式的方法.我似乎无法访问此模块中的方法.知道为什么吗?

Jon*_*röm 64

如果您include使用模块,则该方法将成为实例方法,但如果您extend是模块,则它将成为类方法.

module Const
  def format
    puts 'Done!'
  end
end

class Car
  include Const
end

Car.new.format # Done!
Car.format # NoMethodError: undefined method format for Car:Class

class Bus
  extend Const
end

Bus.format # Done!
Bus.new.format # NoMethodError: undefined method format
Run Code Online (Sandbox Code Playgroud)


Gut*_*nYe 34

module Foo
  def self.hello # This is a class method
    puts "self.hello"
  end

  def hello # When you include this module, it becomes an instance method 
    puts "hello"
  end
end

Foo.hello #=> self.hello

class Bar
  include Foo
end

Bar.new.hello #=> hello
Run Code Online (Sandbox Code Playgroud)