Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • array_count_values

    Posted on October 21st, 2009 RubyLove No comments

    The array_count_values() function in PHP counts the number of instances of each value in an array. array_count_values() returns an associative array using the values of the input array as keys and their frequency in the input as values.

    PHP

    $a = array('a', 'b','a', 'c', 'c');
    $results = array_count_values($a);
    print_r($results);
    /*
    Array (
    	[a] => 2
    	[b] => 1
    	[c] => 2
    )
    */

    To replicate this functionality in Ruby, we need to use a Hash object, since arrays in Ruby don’t use associative key/value pairs.

    Ruby

    a = [ "a", "b", "a", "c", "c" ];
    result = list.inject({}) do |hash, key|
      hash.include?(key) ? hash[key] += 1 : hash[key] = 1;
      hash
    end
     
    p result;
    # => ["a" => 2, "b" => 1, "c" => 2]