1

How can I convert the following

 @results = [{"id"=>"one", "url"=>"/new/file_one.jpg"}, 
             {"id"=>"two", "url"=>"/new/file_two.jpg"}]

to

 @results = {"one" => "/new/file_one.jpg", 
             "two" => "/new/file_two.jpg"}

Should I use "map" or "collect"? Starting with..

@results.map{ |x| x['id']}
1
  • 2
    Your desired @results isn't Ruby at all, what should it really look like? @results = { 'one' => ... } perhaps? Commented Nov 10, 2014 at 23:43

3 Answers 3

3

Using Hash::[]:

@results = [{"id"=>"one", "url"=>"/new/file_one.jpg"},
             {"id"=>"two", "url"=>"/new/file_two.jpg"}]
Hash[@results.map { |x| [x['id'], x['url']] }]
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}

In Ruby 2.1+, you can also use Enumerable#to_h:

@results.map { |x| [x['id'], x['url']] }.to_h
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}
Sign up to request clarification or add additional context in comments.

4 Comments

@igor, BTW, you expect a hash object as a result : {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}, not ["one" => "/new/file_one.jpg", "two" => "/new/file_two.jpg"]. Right?
Whether the OP expected an array with => or {... => ...} isn't too important as Ruby will convert the second to the first anyway: ['a' => 1] # => [{"a"=>1}]
@theTinMan, Nice to learn it. Thank you. But they are different: A hash and an array of a hash.
@falsetru yes, that's what I was looking for, will edit the question, sorry
2

Just iterate over the array and extract the values of each sub-hash:

[
  {"id"=>"one", "url"=>"/new/file_one.jpg"},
  {"id"=>"two", "url"=>"/new/file_two.jpg"}
].map(&:values).to_h 
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}

If your Ruby doesn't support to_h then wrap it all in Hash[...].

Comments

1

Is this what you are looking for?

results.map{ |x| {x['id'] => x['url']} }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.