📄 14 - generating a sequence of numbers.rb
字号:
def fibonacci(limit = nil) seed1 = 0 seed2 = 1 while not limit or seed2 <= limit yield seed2 seed1, seed2 = seed2, seed1 + seed2 endendfibonacci(3) { |x| puts x }# 1# 1# 2# 3fibonacci(1) { |x| puts x }# 1# 1fibonacci { |x| break if x > 20; puts x }# 1# 1# 2# 3# 5# 8# 13#---class Range def each_slow x = self.begin while x <= self.end yield x x = x.succ end endend(1..3).each_slow {|x| puts x}# 1# 2# 3#---class Fixnum def double_upto(stop) x = self until x > stop yield x x = x * 2 end endend10.double_upto(50) { |x| puts x }# 10# 20# 40#---def oscillator x = 1 while true yield x x *= -2 endendoscillator { |x| puts x; break if x.abs > 50; }# 1# -2# 4# -8# 16# -32# 64#---1.5.step(2.0, 0.25) { |x| puts x }# => 1.5# => 1.75# => 2.0#---def zeno(start, stop) distance = stop - start travelled = start while travelled < stop and distance > 0 yield travelled distance = distance / 2.0 travelled += distance endendsteps = 0zeno(0, 1) { steps += 1 }steps # => 54#---
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -