Search code examples
ruby-on-railsarraysrubyruby-on-rails-3actioncontroller

RoR - Removing an array element from ActionController::Parameters


In my Rails 3.2 application, I am getting the params variable in my controller as follows:

params.class         => ActionController::Parameters
params[:a].class     => ActionController::Parameters
params[:a][:b].class => Array
params[:a][:b]       => ['1', '2', '3', '4']

When I try to delete a value in the array, it's not reflecting correctly.

e.g.

params[:a][:b].delete('1') 
=> "1"

But when I again query it, there is no change in it.

params[:a][:b]   => ['1', '2', '3', '4']

Although, if I reassign it to a variable, it's working fine.

arr = params[:a][:b]
arr.delete('1')
=> "1"

arr
=> ['2', '3', '4']

Any idea why I cannot update the params object directly?


Solution

  • params[:a][:b].tap { |ary| ary.delete('1') }
    #=> ['2', '3', '4']
    

    To change the value of params[:a][:b] you'd want assign it a new value:

    params[:a][:b] = params[:a][:b].tap { |ary| ary.delete('1') }