2

Input:-

array = [{"name"=>"id", "value"=>"123"}, 
         {"name"=>"type", "value"=>"app"}, 
         {"name"=>"codes", "value"=>"12"}, 
         {"name"=>"codes", "value"=>"345"}, 
         {"name"=>"type", "value"=>"app1"}] 

sample_hash = {}

Function:-

array.map {|f| sample_hash[f["name"]] = sample_hash[f["value"]] }

Result:-

sample_hash

 => {"id"=>"123", "type"=>"app", "codes"=>"345"} 

But i need expected result should be like below:-

sample_hash

 => {"id"=>"123", "type"=>["app","app1"], "codes"=>["12", "345"]} 

How can i get my expected output?

2
  • 1
    Although it's not exactly what you've asked for, it will make you hash easier and nicer to work with if you have an array even for the keys that only have one value e.g. "id" => ["123"] - that way when getting values from the hash you won't have to check if you have got back a string or an array. Commented Apr 7, 2015 at 8:00
  • 1
    @mikej Agree with you. API consistency matters and helpful. Commented Apr 7, 2015 at 8:04

3 Answers 3

1

You can initialize sample_hash using the new {|hash, key| block } Hash constructor to make the values in this hash be initialized to empty arrays by default. This makes it easier in the second phase, where each value in the initial data set is appended to the array of values indexed under the corresponding "name":

sample_hash = Hash.new { |h, k| h[k] = [] }
array.each { |f| sample_hash[f['name']] << f['value'] }

Try it online

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

Comments

1

@w0lf is correct. Same, but different construct.

array.each_with_object({}) do |input_hash, result_hash|
  (result_hash[input_hash['name']] ||= []) << input_hash['value']
end

Comments

0

See this :

array.inject({}) do |ret, a| 
    ret[a['name']] = ret[a['name']] ? [ret[a['name']], a['value']] : a['value']  
    ret
end

o/p : {"id"=>"123", "type"=>["app", "app1"], "codes"=>["12", "345"]}

Comments

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.