0

Can somebody help me to convert the following array to a hash with the following format?

Array

[["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]]

Hash

search=>{"checkbox_2"=>"on", "checkbox_1"=>"on"}
0

2 Answers 2

2
xs = [["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]]
search = {:search => xs.map { |n, h| h }.inject(:merge)}
# {:search=>{"checkbox_2"=>"on", "checkbox_1"=>"on"}}
Sign up to request clarification or add additional context in comments.

2 Comments

How about { :search => xs.map(&:last).inject(:merge) }?
@Michael: yeah, or (&:second) on Rails. Thing is, when getting from pairs I feel it's more clear to de-structure (in other languages those elements would be tuples, not arrays).
1
arr = [["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]] 
hash = Hash[arr.flatten.select{|e| e.is_a? Hash}.collect{|e| e.to_a.flatten}]
=> {"checkbox_2"=>"on", "checkbox_1"=>"on"}

1 Comment

this way would be ok if the hash appeared in any position but if it's always in the second position, well, it's unnecessarily convoluted.

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.