Reading and writing Sinatra parameters using characters, for example. Titles [: identifier]

My form receives data through POST. When I do puts params, I see:

{"id" => "123", "id2" => "456"}

now the commands:

puts params['id']    # =>  123
puts params[:id]     # =>  123

params['id'] = '999'
puts params          # => {"id" => "999", "id2" => "456"}

but when i do this:

params[:id] = '888'
puts params

I get

{"id" => "999", "id2" => "456", :id => "888"}

It works great in IRB:

params
# => {"id2"=>"2", "id"=>"1"}

params[:id]
# => nil

params['id']
# => "1"

Why can I read the value with :id, but not set the value with this?

+5
source share
1 answer

Ruby hashes allow you to use arbitrary objects as keys. Since strings (for example, "id") and characters (for example, :id) are separate types of objects, a hash can have as a key both a string and a character with the same visual content without conflict:

irb(main):001:0> { :a=>1, "a"=>2 }
#=> {:a=>1, "a"=>2}

JavaScript, .

- ( GET POST) , Sinatra "", , . default_proc, to_s , .

:

def indifferent_hash
  Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
end

[]=(key, val), .

+12

All Articles