2014-10-29 35 views
2

我有一個數組作爲哈希值:轉換字符串數組成鍵值對

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

我試圖找到一種方法來在陣列中的每個元素轉換爲這樣的事情:

:centre_id => 1 
:id => 1 

我嘗試不同的方式加載,但我似乎無法找到一個很好的清潔方法來做到這一點:

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

這是我想實現:

-{"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? 

使用此:

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

幫助將非常感激。

+0

你的輸入數據是什麼樣的? – tadman 2014-10-29 17:47:10

+1

@tadman [{:request_method =>:get,:path =>「/ leisure/1/activity/1」,:controller =>「venues」,:params => [「:centre_id」,「:id」 ],::controller_constant =>「VenuesController」,:action =>「activity」}, – user3868832 2014-10-29 17:55:42

+0

我想實現get(「/ game/1」)。 ) – user3868832 2014-10-29 17:56:37

回答

4

執行如下: -

紅寶石2.1或以上,以下使用方法: -

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

紅寶石2.0以下,以下使用方法: -

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

一個更容易閱讀的方式可能是'x.sub(/ \ A:/,'')。to_sym' – tadman 2014-10-29 17:40:16

+0

@tadman感謝教學..甜蜜的事情。我在正則表達式中表現不好,所以總是儘量避免.. :-( – 2014-10-29 17:41:50

+0

這是你應該重點練習的東西,像[Rubular](http://rubular.com/)這樣的網站是測試的好方法並學習,一旦你掌握了它們,你會發現它們一直都派上用場。 – tadman 2014-10-29 17:43:43

1

如果

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

以下內容之一可能有幫助:

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}} 

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} 

第二修改h。如果你不希望發生這種情況,你首先需要h.dup

如果a是一個數組,您可以使用Ruby 2.1+替換Hash[a]a.to_h