Skip to content

Instantly share code, notes, and snippets.

@SyunWatanabe
Created February 20, 2020 01:09
Show Gist options
  • Select an option

  • Save SyunWatanabe/13efef3b036564f9b689cc231b0d5b5e to your computer and use it in GitHub Desktop.

Select an option

Save SyunWatanabe/13efef3b036564f9b689cc231b0d5b5e to your computer and use it in GitHub Desktop.
# count 再実装
class Array
def count(*args)
if block_given?
num = 0
each { |i| num += 1 if yield(i) }
num
elsif args.empty?
size
else
num = 0
each { |i| num += 1 if i == args[0] }
num
end
end
end
puts [1, 2, 4, 2].count #=> 4
puts [1, 2, 4, 2].count(2) #=> 2
puts [1, 2, 4, 2].count(&:even?) #=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment