Tips – Set Default Value for A Hash

RubyOnRails,Tips 10 六月 2010 | View Comments

Can hash have a default value, when it doesn’t have a key?

Answer is yes!

h = Hash.new("default")
h["wrong_value"] # => "default"


Tagged in , ,

Why we can get params values by both symbol and string

RubyOnRails 15 二月 2010 | View Comments

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:

def some_action
  params.symbolize_keys!
end

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:

  h = HashWithIndifferentAccess.new
  h["allen"] = "wei"
  puts h["allen"] # print "wei"
  puts h[:allen]  # print "wei"
You don’t need symbolize_keys!!.

Tagged in , , ,

Ads Plugin created by Jake Ruston's Wordpress Plugins - Powered by and football database.