Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Last active August 29, 2015 13:56
Show Gist options
  • Save pinzolo/9086037 to your computer and use it in GitHub Desktop.
Save pinzolo/9086037 to your computer and use it in GitHub Desktop.
配列を作らずに条件を満たす最初からの個数を数える
module Enumerable
def count_while
return to_enum(:count_while) unless block_given?
count = 0
each do |item|
if yield(item)
count += 1
else
return count
end
end
count
end
def count_until
return to_enum(:count_until) unless block_given?
count = 0
each do |item|
if yield(item)
return count
else
count += 1
end
end
count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment