Tips – Set Default Value for A Hash
Can hash have a default value, when it doesn’t have a key?
Answer is yes!
h["wrong_value"] # => "default"
Can hash have a default value, when it doesn’t have a key?
Answer is yes!
Today, I met a weird bug converting params to a hash only has symbol keys.
I see there is a method which in ActiveSupport. symbolize_keys!!, convert all keys of hash to symbol.
So I did this:
But after print params, I found symbolize_keys! doesn’t work. The keys in params still String.
After some googling, I find that class of params is not hash, it is HashWithIndifferentAccess
Then I find symbolize_keys! method just return self
The description of this class is:
bq. This class has dubious semantics and we only have it so that people can write params[:key] instead of params[âkeyâ] and they get the same value for both keys.
I realized that’s why we can get values from params by both Symbol and String
So You can also use this powerful tool:
Ads Plugin created by Jake Ruston's Wordpress Plugins - Powered by and football database.