0

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.

pierallard
  • 3,326
  • 3
  • 21
  • 48
  • Possible duplicate of http://stackoverflow.com/questions/5861532/if-i-have-a-hash-in-ruby-on-rails-is-there-a-way-to-make-it-indifferent-access – Marcelo De Polli Apr 04 '13 at 14:44

1 Answers1

3

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
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • I forgot something: I'm with Rails 2 ; with_indifferent_access is not available... – pierallard Apr 04 '13 at 14:40
  • Sorry, I do a wrong click. I just remove it. with_indiferrent_access have just moved from class to another between Rails 2 and 3. Thanks ! – pierallard Apr 04 '13 at 14:44
  • yes it's there: https://github.com/rails/rails/blob/2-3-stable/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb#L135 – apneadiving Apr 04 '13 at 14:44