0

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] }]
  • I understand line 1 creats a hash which I believe is similar to a dictionary in python.
  • Line 2 loops through my json data set a adds a new key and value pair if none exits and increments the count if 1 does exist.
  • What does the 3rd line do?
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there documentation for .map. method. I tried looking here, ruby-doc.org/core-2.3.1/Hash.html, but found nothing.
In recent Ruby versions you could write counted.transform_values!(&:to_s)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.