`
liss
  • 浏览: 826370 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

ruby学习笔记(4)-Iterator

    博客分类:
  • Ruby
阅读更多

class TItem
  attr_reader :name
  def initialize(name)
   @name=name
 end
 def Fibonacci (max)
   #初始化
   i1,i2=1,1
   #循环构建斐波纳契数列
   while i1<max
    #yield关键字,声明执行块中的内容
    #在这儿是传入int=i1并且打印
    yield i1
    #这样的赋值方式写起来很简洁
    i1,i2=i2,i1+i2
   end
  end
end
arr=Array.new
arr.push(TItem.new('first'))
arr.push(TItem.new('second'))
arr.push(TItem.new('third'))

#依旧支持循环
for i in 0...arr.length
  puts arr[i].class==TItem #true
end
#新的迭代方法
titem=arr.find{ |titem| titem.name=='first'}
#打印斐波纳契数列
#{}块中的内容将被TItem.Execute调用
titem.Fibonacci(100){|int| print int,' '}#1 1 2 3 5 8 13 21 34 55 89
#each列举每个元素
arr.each{|titem| puts titem.name} #[first,second,third]
#collect和each是同样的方法
arr.collect{|titem| puts titem.name.succ}#firsu.secone.thire
#书上说应该是string first ,second third
#但是示例出来只有string first ,second.不知为何
#inject的参数是为str赋初值
str=nil
arr.inject("string"){|str ,titem| str+" "+titem.name} #string first second
puts str

#定义另一个数组
arr2=[TItem.new('1'),TItem.new('2'),TItem.new('3')]
#定义方法
def dbexecute(*arrarg)
  puts arrarg.length #2
  yield arrarg[0] #firstsecondthird
  yield arrarg[1] #123
end
#yield迭代执行
dbexecute(arr,arr2) do |array|
  array.each{|titem| print titem.name }
  puts
end


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/blackant2/archive/2006/11/30/1422831.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics