自定义可枚举类型
Coddy 面向 Kotlin 开发者的 Ruby 课程的第 40 课,共 48 课。
Kotlin Iterator 使用 hasNext 和 next,耗尽后调用 next 会失败。Ruby 的迭代方法在没有代码块时通常会返回 Enumerator,耗尽后调用 next 会引发 StopIteration。两者都会保留遍历状态。枚举器不会自动复制集合;应明确规定重复遍历和修改策略。
Kotlin:完整程序
fun main(){
val cursor=(2 until 5).iterator();println(cursor.next());println(cursor.next())
}
Ruby:完整程序
it = (2...5).each
puts it.next
puts it.next挑战
简单定义 Window(values),复制传入的整数数组,包含 Enumerable 并实现 each。有代码块时,按顺序 yield 各个值并返回 self;没有代码块时,返回 Enumerator。solve 使用对象的 Enumerable 方法返回奇数值之和。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,还会独立检查所需的公共 API。
你的代码写在 exercise.rb、window.rb 中。main.rb 存放提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'window'
def check(value)
raise 'Public API check failed' unless value
end
v = [8, 2]; w = Window.new(v); v << 9
seen = []; check(w.each { |n| seen << n }.equal?(w))
check(seen == [8, 2] && w.each.to_a == [8, 2] && w.map { |n| n + 1 } == [9, 3])
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器