I noticed that in Ruby on Rail access to the hash value can be obtained in two ways: params["product"] and params[:product] . These methods are similar.
How this is implemented, because in Ruby hash["k"] and hash[:k] are two different things.

    1 answer 1

    Parameters in Ruby on Rails are implemented through the Object::HashWithIndifferentAccess , which inherits from Hash . Its peculiarity lies in the fact that it automatically brings symbolic keys to a string value, so you can use both a character and a string to access the parameter.

    If you look at the implementation of this class, you will see that almost all methods for working with keys are overloaded, for example

     ... def [](key) super(convert_key(key)) end ... def convert_key(key) key.kind_of?(Symbol) ? key.to_s : key end ... 
    • And these methods can be defined in any object, giving it the ability to work with the same syntax. - D-side
    • Well, the parameters are a separate class. In the 4 rails they were inherited from HashWithIndifferentAccess , in the fifth - an independent class. - anoam
    • @anoam if not difficult, please develop your thought either in a comment or in a separate answer (for which you can vote). As far as I can see from the documentation Object :: HashWithIndifferentAccess is part of ROR 5.0. - cheops
    • @cheops yes, this is part of ActiveSupport . But params has a slightly different type: ActionController::Parameters . And in my opinion, he was also on the fourth rails. - D-side
    • @cheops, in fact, there is nothing to develop here. Everything has been said. To use [] and []= it is necessary and sufficient to define appropriate methods. I just clarified that in 4th rails this was done at the expense of inheritance from HashWithIndifferentAccess , in the fifth - they refused to inherit and explicitly defined the methods. - anoam