类与实例
Coddy 面向 Python 开发者的 Ruby 课程的第 27 课,共 48 课。
Python 的 __init__ 和 Ruby 的 initialize 会在分配内存后初始化实例。Ruby 的 new 通常会调用 initialize,而实例变量以 @ 符号开头,并属于特定对象。实例方法可以在没有显式接收者的情况下读取这些变量。Python 要求在方法定义中使用 self;Ruby 则会隐式提供 self。未定义的实例变量会求值为 nil,因此要初始化方法所依赖的状态。这个示例有一个固定的文本属性,而不是可变的数字计数器。
Python:完整程序
class Greeting:
def __init__(self, word):
self.word = word
def text(self):
return self.word.upper()
print(Greeting("hi").text())Ruby:完整程序
class Greeting
def initialize(word)
@word = word
end
def text
@word.upcase
end
end
puts Greeting.new("hi").text挑战
简单定义 Counter,包含 initialize(start)、value 和 add(amount)。add 只会更改该实例,并返回它的新值。solve 读取一个起始值和后续的增量,并返回最终值。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查必需的公开 API。
你的代码写在 exercise.rb、counter.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'counter'
def check(value)
raise 'Public API check failed' unless value
end
a = Counter.new(4); b = Counter.new(-2)
check(a.add(3) == 7 && a.value == 7 && b.value == -2)
check(b.add(9) == 7 && a.value == 7)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器