Ruby迭代器

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

在方法内容,block能够被yield语句调用ui

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

输出结果:code

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, ' '}

输出结果以下:three

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

在来一个例子:get

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))

在来一个例子:test

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变量

相关文章
相关标签/搜索