`

娃娃鸭学Ruby-33、迭代器

阅读更多
虽然可用while,until和for循环
但还是更倾向于用迭代器

3.times{puts "thank you!"
data.each{|x| puts x}
[1,2,3].map{|x| x*x}

factorial=1
2.upto(n) {|x| factorial*=x}
times,each,map,upto都是迭代器
yield语句就是这些迭代器背后复杂的控制结构。yield语句从迭代器中临时地将程序控制权返回给那个调用迭代器的方法,具体来说,程序的控制流会从迭代器转移到那个与迭代器调用相关联的代码块中,当程序执行完代码块之后,迭代器方法重新获得控制权并且从位于yield语句之后的第一个语句开始继续执行。


数值迭代器
Kernel类的loop方法 像一个无限循环,不断执行相关代码块,直到遇到 return ,break
Integer类 三个迭代器
      upto
                    4.upto(6) {|x| print x} # prints "456"
      downto 类似upto
      times
                   3.times{|x| print x} # prints "012"
            n.times和0.upto(n-1)是等价的
Numeric类
        step
            0.step(Math::PI,0.1} {|x| puts Math.sin(x)}

2011-4-19 14:21 danny
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics