2

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.

3
  • What does your input data look like? Commented Oct 29, 2014 at 17:47
  • 1
    @tadman [{:request_method=>:get, :path=>"/leisure/1/activity/1", :controller=>"venues", :params=>[":centre_id", ":id"], :controller_constant=>"VenuesController", :action=>"activity"}, Commented Oct 29, 2014 at 17:55
  • i want to achieve something like get("/game/1").should route_to("game#show", :id => 1) Commented Oct 29, 2014 at 17:56

2 Answers 2

4

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}
Sign up to request clarification or add additional context in comments.

6 Comments

@tadman Thanks for teaching.. sweet thing. I am not well in regex, so always try to avoid.. :-(
It's something you should make a point to practice. A site like Rubular is a great way to test and learn. Once you've got a handle on them you'll find they come in handy all the time.
Hey guys, thanks for your help, but it renders error undefined method `to_h' for [[:centre_id, 1], [:id, 1]]:Array
The to_h method might be Rails specific. An alternative is to use Hash[ ... ] instead of (...).to_h
@user3868832 your Ruby version ?
|
1

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+.

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.