2gua 发表于 2010-12-07 11:03

[技巧]Include与Extend的比较

本帖最后由 2gua 于 2010-12-07 11:36 编辑

你可以用include或extend来MixIn(混入)module的方法到class。
它俩的不同在于:

    include使得module的方法被类实例使用;
    extend使得module的方法被类本身使用。

举例:

module Greetings
def say_hello
    puts "Hello!"
end
end

class Human
include Greetings
end

Human.new.say_hello # => "Hello!"
Human.say_hello   # NoMethodError

class Robot
extend Greetings
end

Robot.new.say_hello # NoMethodError
Robot.say_hello   # => "Hello!"

如果你想了解更多关于include和extend比较的信息,推荐你看看以下资源:

[*]What is the difference between include and extend in Ruby? on Stack Overflow.[*]Include vs Extend in Ruby by John Nunemaker[*]Ruby extend and include by Jay Fields
页: [1]
查看完整版本: [技巧]Include与Extend的比较