本帖最后由 taroxd 于 2014-2-28 20:35 编辑
好多语法糖~ 学习了
话说,ruby的facets这个gem里面有更多糖……
下面这个我觉得也挺常用的吧
module Enumerable def sum(base = 0) block_given? ? inject(base) {|a, e| a + yield(e) } : inject(base, :+) end # 元素之积(Array类已存在product方法) def pdt(base = 1) block_given? ? inject(base) {|a, e| a * yield(e) } : inject(base, :*) end # base取0.0即可做浮点运算 def average(base = 0, &block) sum(base, &block) / [count, 1].max end end
module Enumerable
def sum(base = 0)
block_given? ? inject(base) {|a, e| a + yield(e) } : inject(base, :+)
end
# 元素之积(Array类已存在product方法)
def pdt(base = 1)
block_given? ? inject(base) {|a, e| a * yield(e) } : inject(base, :*)
end
# base取0.0即可做浮点运算
def average(base = 0, &block)
sum(base, &block) / [count, 1].max
end
end
|