never_odd_or_even
never_odd_or_even

Reputation: 314

Understanding Ruby Code

I need some help understanding the below ruby code.

counted = Hash.new(0)
parsed_reponse["result"]["data"].each { |h| counted[h["version"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]

Upvotes: 0

Views: 66

Answers (1)

Ilya
Ilya

Reputation: 13487

Your last line just converts all values to String:

Hash[{a: 2, b: 3}.map {|k, v| [k, v.to_s]}]
#=> {:a=>"2", :b=>"3"}

I would refactor it to:

counted.transform_values!(&:to_s) # for ruby >= 2.4
#=> {:a=>"1", :b=>"2"}

Or for older versions:

counted.each { |k, v| counted[k] = v.to_s }

Because:

  • counted.map {|k,v| [k,v.to_s] } - creates new array of arrays
  • Hash[result] - creates new Hash object from result array.

Both steps are redundant, you can just modify existing hash.

Upvotes: 1

Related Questions