This was a nice conside one to generate a Hash count from an Array.
array = [1, "hello", 1, "world", "hello"]
counts = {}
array.each do |value|
counts[value] ||= 0
counts[value] += 1
end
Here it is as an Array method:
class Array
def count_values
counts = {}
each do |value|
counts[value] ||= 0
counts[value] += 1
end
counts
end
end
Here’s the php.net example:
array = [1, "hello", 1, "world", "hello"]
p array.count_values