2013-04-04 28 views
0

控制器功能receivent參數等如何擁有與'params'函數相同的行爲?

{"v1" => { "v2" => "1", "v3" => "" }, "v4" => "true"} 

params功能允許使用

  • x = params[:v1],相當於​​
  • if params[:v4],相當於["true", "1"].include?(params["v4"])
  • if (params[:v1][:v2] == 1),相當於params["v1"]["v2"] == "1"

有什麼方法可以比params函數有其他的數據行爲嗎?

我希望能夠寫類似的東西...

my_params = {"v1" => { "v2" => "1", "v3" => "" }, "v4" => "true"} 
x = my_params[:v1] 
if my_params[:v4] 
if (my_params[:v1][:v2] == 1) 

或者具有功能some_function

我在Rails的2

+0

可能的重複http://stackoverflow.com/questions/5861532/if-i-have-a-hash-in-ruby-on-rails-is-there-a-way-to-make-it-無所謂 - 訪問 – depa 2013-04-04 14:44:18

回答

3

你想要一個hash with indifferent access

h = { a: { b: 1, 'c' => 2 } } 
=> {:a=>{:b=>1, "c"=>2}} 
h[:a][:c] 
=> nil 


h2 = h.with_indifferent_access 
=> {"a"=>{"b"=>1, "c"=>2}} 

h2['a'][:c] 
=> 2 
h2[:a][:c] 
=> 2 
+0

我忘了一些東西:我與Rails 2; with_indifferent_access不可用... – pierallard 2013-04-04 14:40:47

+0

,這值得-1? – apneadiving 2013-04-04 14:41:18

+0

對不起,我做了一個錯誤的點擊。我只是刪除它。 with_indiferrent_access剛剛從Rails 2和3之間的類中移動到另一個。謝謝! – pierallard 2013-04-04 14:44:18

相關問題