Search code examples
ruby-on-railsruby-on-rails-2

How to have the same behavior than 'params' function?


Controller functions receivent parameters like

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

The params function allows to use

  • x = params[:v1], equivalent to x = params["v1"]
  • if params[:v4], equivalent to ["true", "1"].include?(params["v4"])
  • if (params[:v1][:v2] == 1), equivalent to params["v1"]["v2"] == "1"

Is there any method to have the behavior than params function, but with other datas ?

I want to be able to write something like that...

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

Or with a function some_function

x = some_function(my_params)[:v1]
if some_function(my_params)[:v4]
if some_function(my_params)[:v1][:v2] == 1)

I'm in Rails 2.


Solution

  • You want a 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