class Language
def initialize(name, creator)
@name = name
@creator = creator
end
def description
puts "I'm #{@name} and I was created by #{@creator}!"
end
end
ruby = Language.new("Ruby", "Yukihiro Matsumoto")
python = Language.new("Python", "Guido van Rossum")
javascript = Language.new("JavaScript", "Brendan Eich")
ruby.description
python.description
javascript.description
- 类名首字母大写,NewClass (方法名首字母小写,多个单词用下划线连接)
- 初始化函数 initialize, 参数为name, creator
- 实例变量赋值@name = name (python self.name = name)
- 创建实例 ruby = Language.new("Ruby", "Yukihiro Matsumoto")
- 调用类函数 ruby.description
- @关键字 + 变量名 表示该变量为实例变量