block example in Ruby

April 12, 2015
Ruby

这几天看Ruby,挺有意思的,比如Block的用法:

#!/usr/bin/ruby 

def total2(from, to, &block) 
  result = 0
  from.upto(to) do |num|
    if block 
      result += block.call(num)
    else 
      result += num
    end
  end
  return result
end

p total2(1, 10)
p total2(1, 10) {|num| num * 2}
p total2(1, 10) {|num| num ** 2}

上面的三个输出分别是

55
110
385

函数total2中的第三个传递块的参数叫做Proc参数

comments powered by Disqus