user3868832
user3868832

Reputation: 620

Converting an array of strings into a key-value pair

I have an array as the value of a hash:

:params=>[":centre_id", ":id"]

I am trying to find a way to convert each element of the array to something like this:

:centre_id => 1
:id => 1

I tried loads of different ways but I can't seem to find a nice clean way to do it:

"#{route[:params].map {|x| x.parameterize.underscore.to_sym => '1'}}"

This is what I am trying to achieve:

-{"controller"=>"venues", "action"=>"activity, {:centre_id=>1, :id=>1}"}
+{"controller"=>"venues", "action"=>"activity", "centre_id"=>"1", "id"=>"1"} << this one

    string or symbol doesn't matter does it?

Using this:

expect(route[:request_method] => route[:path]).to route_to "#{route[:controller]}##{route[:action]}, #{Hash[route[:params].map {|x| [x.sub(/\A:/,'').to_sym, 1] }]}" 

Help would be much appreciated.

Upvotes: 2

Views: 1223

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110665

If

h = { :params=>[":centre_id", ":id"], :animals=>[":dog", ":cat", ":pig"] }

one of the following may be helpful:

h.merge(h) { |_,v,_| Hash[v.map { |s| [s[1..-1].to_sym,1] }] }
  #=> {:params=>{:centre_id=>1, :id=>1}, :animals=>{:dog=>1, :cat=>1, :pig=>1}}

or

Hash[h.keys.map { |k| h.delete(k).map { |s| [s[1..-1].to_sym,1] } }.flatten(1)]
  #=> {:centre_id=>1, :id=>1, :dog=>1, :cat=>1, :pig=>1}

The second modifies h. If you don't want that to happen, you'll need to h.dup first.

If a is an array, you can replace Hash[a] with a.to_h with Ruby 2.1+.

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

Do as below :-

Ruby 2.1 or above, use below :-

route[:params].map {|x| [x.sub(/\A:/,'').to_sym, 1] }.to_h
# => {:centre_id => 1, :id => 1}

Ruby 2.0 or below, use below :-

Hash[route[:params].map {|x| [x.sub(/\A:/,'').to_sym, 1] }]
# => {:centre_id => 1, :id => 1}

Upvotes: 4

Related Questions