Tuesday, 15 May 2012

ruby on rails - Kind of ugly- default value for non-existent hash key? -


I am working with the API which gives a yes to represent the product: < Pre> Prod = API.getProduct (id) prod ["name"] = & gt; "Widget"

causes this problem because all products do not have the same attribute pages, so I'm doing a lot to catch myself an error - something Products will have size or colors , nothing will happen.

prod ["non-existent attribute"] = & gt; What is the easiest way to get it? "NA"?

As Dave Newton said, you can add default value to hash creator:

  hash = hash.nu {| Hash, key | Hash [key] = "na"} hash [: anything] == "NA" # = & gt; Use the correct   

or #default method:

  hash = hash.new hash.default = "NA" hash [: Anything] == "NA" # = & gt; Quick Start   

Edit is quick syntax for setting a default value when starting a hash:

  hash = hash.New ("NA") hash [: anything] == "NA" # = & gt; True    

No comments:

Post a Comment