ruby学习笔记(4)-Iterator

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

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值