Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Created May 26, 2011 12:01
Show Gist options
  • Save Sephi-Chan/992992 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/992992 to your computer and use it in GitHub Desktop.
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb
index 4cd9bfa..b6ccef5 100644
--- a/activesupport/lib/active_support/core_ext/array/grouping.rb
+++ b/activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -97,4 +97,16 @@ class Array
results
end
end
+
+
+ # Count occurences of values in the array.
+ # Return it as a hash.
+ #
+ # [1, 1, "foo", :bar, 1, :bar].count_occurrences # => {1 => 3, "foo" => 1, :bar => 2}
+ def count_occurrences
+ inject({}) do |hash, key|
+ hash.include?(key) ? hash[key] += 1 : hash[key] = 1;
+ hash
+ end
+ end
end
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index 0e5407b..576adf0 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -464,3 +464,29 @@ class ArrayWrapperTests < Test::Unit::TestCase
assert_equal DoubtfulToAry.new.to_ary, Array.wrap(DoubtfulToAry.new)
end
end
+
+class ArrayCountOccurrencesTests < Test::Unit::TestCase
+ def test_count_occurrences_with_scalar
+ source = [ 1, 1, "foo", :bar, 1, :bar ]
+ result = { 1 => 3, "foo" => 1, :bar => 2 }
+ assert_equal result, source.count_occurrences
+ end
+
+ def test_count_occurrences_with_hash
+ source = [ { "foo" => "bar" }, { "foo" => "bar" }, { :bar => :foo } ]
+ result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1 }
+ assert_equal result, source.count_occurrences
+ end
+
+ def test_count_occurrences_with_hash_and_arrays
+ source = [ { "foo" => "bar" }, { "foo" => "bar" }, { :bar => :foo }, [ 1, 2, 3 ], [ 1, 2, 3 ], [ 4 ] ]
+ result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1, [ 1, 2, 3 ] => 2, [ 4 ] => 1 }
+ assert_equal result, source.count_occurrences
+ end
+
+ def test_count_occurrences_with_everything
+ source = [ 8, { "foo" => "bar" }, { "foo" => "bar" }, 8, { :bar => :foo }, [ 1, 2, 3 ], [ 1, 2, 3 ], [ 4 ], :foo ]
+ result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1, [ 1, 2, 3 ] => 2, [ 4 ] => 1, 8 => 2, :foo => 1 }
+ assert_equal result, source.count_occurrences
+ end
+end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment