Calvin
Calvin

Reputation: 3312

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}

Upvotes: 1

Views: 75

Answers (2)

Wand Maker
Wand Maker

Reputation: 18762

Here is a solution to compute both the values in single iteration (some sort of one liner)

r1,r2 = hash.reduce([nil, 0]){|m,(_,v)| [[m[0], v.to_s].compact.join(","),m[-1]+v]}
#=> ["2,3,1", 6]

Upvotes: 0

Agis
Agis

Reputation: 33626

You can do it like this:

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

Upvotes: 9

Related Questions