Created
February 19, 2014 04:54
-
-
Save pinzolo/9086251 to your computer and use it in GitHub Desktop.
Enumerableに合計取得系のメソッドを追加する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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