Ruby迭代器

699 查看

Block紧跟方法调用,当遇到一个Block时,并不立刻执行其中的代码。ruby会记住block出现时的上下文(局部变量,当前对象等),然后执行方法调用。

在方法内容,block可以被yield语句调用

def three_times
    yield
    yield
    yield
end
three_times { puts "Hello" }

输出结果:

Hello
Hello
Hello

下面我们来看一个使用Block使用局部变量的例子

def fib_up_to(max)
    i1, i2 = 1, 1
    while i1 <= max
        yield i1
        i1, i2 = i2, i1 + i2        
    end
end

fib_up_to(1000) {|i1| print i1, ' '}

输出结果如下:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

在来一个例子:

def n_times(thing)
    #这里我们返回一个Proc类的对象
    lambda { |n| thing * n }        
end

def test(n, block)
    #使用.call方法调用Proc对象
    block.call(n)
end

puts test(2,n_times(23))

在来一个例子:

print "(t)imes or (p)lus: "
times = gets
print "number: "
number = Integer(gets)
if times =~ /^t/
    calc = lambda { |n| n*number }
else
    calc = lambda { |n| n+number }
end

puts (1..10).collect(&calc).join(', ')

lambda的意思是:Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
当我们使用&calc的时候就是相当于使用了上面的.call方法调用block