ruby里的require、load与include

require、load类似java中的import,引入别的文件中定义的类
include用于实现mixin,引入module。
# Mixins.rb
module D
	def initialize(name)
    @name =name
	end
  def to_s
		@name
	end
end

module Debug
  include D
	# Methods that act as queries are often
	# named with a trailing ?
	def who_am_i?
		"#{self.class.name} (\##{self.object_id}): #{self.to_s}"
	end
end

class Phonograph
	# the include statement simply makes a reference to a named module
	# If that module is in a separate file, use require to drag the file in
	# before using include
	include Debug
	# ...
end

class EightTrack
	include Debug
	# ...
end

ph = Phonograph.new("West End Blues")
et = EightTrack.new("Real Pillow")
puts ph.who_am_i?
puts et.who_am_i?


require、load 引用的文件需用引号引起来,也可以使用String对象

a='motorcycle'
require a
m = MotorCycle.new('Yamaha', 'red')

A module may contain constants,methods and classes
No instances

你可能感兴趣的:(Ruby)