Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Created February 19, 2014 04:54
Show Gist options
  • Save pinzolo/9086251 to your computer and use it in GitHub Desktop.
Save pinzolo/9086251 to your computer and use it in GitHub Desktop.
Enumerableに合計取得系のメソッドを追加する
module Enumerable
def sum
total = 0
each { |item| total += block_given? ? yield(item) : item }
total
end
def sum_while
return to_enum(:sum_while) unless block_given?
total = 0
each do |item|
if yield(item)
total += item
else
return total
end
end
total
end
def sum_until
return to_enum(:sum_until) unless block_given?
total = 0
each do |item|
if yield(item)
return total
else
total += item
end
end
total
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment