Calvin Calvin - 6 months ago 8
Ruby Question

Is there a one liner or more efficient way to get this done?

Given a hash, for example:

hash = { "fish" => 2, "cat" => 3, "dog" => 1 }


I need to get:


  1. A comma separated string for all the values, E.g. "2,3,1"

  2. An integer that hold the total sum of the values, E.g. 6



My current code:

value_string = hash.map { |k,v| "#{v}"}.join(',')
sum = 0
hash.map { |k,v| sum += v}

Answer

You can do it like this:

hash.values.join(",") # => "2,3,1"
hash.values.inject(:+) # => 6