I've been confused in the past about the behavior of Ruby's Hash constructor. Now that I've looked at the documentation, I have to say I think it violates the principle of least surprise.
A default hash returns nil any time you access a key with no set value. The default value can be changed through the constructor. This can be useful when you want to do something like this...
>> brownie_points = {}=> {}>> brownie_points[:zack] += 2NoMethodError: undefined method `+' for nil:NilClass>> brownie_points.default=> nil
>> brownie_points = Hash.new(0)=> {}>> brownie_points.default=> 0>> brownie_points[:zack] += 3=> 5>> brownie_points[:sam]=> 0
We can all agree that this is useful. Moreover, developers will rarely use the constructor, because the ruby language construct {} is so much more elegant. I just don't see myself doing a lot of this...
attributes = {:key_one => :value_one}Hash.new(attributes)
That being said, the prime directive isn't we aren't using that method let's do something with it. It's the principle of least suprise. Not only that, but it violates a pretty universal convention in all of OO that objects' constructors will accept values that make up their initial state. Instead, it accepts the value to return when you ask for something outside it's current state.
To work around this problem, ruby includes a class-level method [].
>> Hash[:frank => 'friendly', :zack => 'here let me thread that for you', :panda => :zen]=> {:zack=>"here let me thread that for you", :frank=>"friendly", :panda => :zen}
Fortunately most programmers will never run in to this issue because of the {} construct, which is more fun anyway.
4 comments:
Today is my lucky day :)
Apple is giving review copies of iPad to 100 lucky person. Go to http://bit.ly/d9QOON and apply for it.
[url=http://www.ganar-dinero-ya.com][img]http://www.ganar-dinero-ya.com/ganardinero.jpg[/img][/url]
[b]Necesitas ganar dinero y no sabes que hacer[/b]
Hemos encontrado la mejor guia en internet de como trabajar en casa. Como nos ha sido de interes para nosotros, tambien les puede ser de interes para ustedes. No son unicamente formas de ganar dinero con su pagina web, hay todo tipo de metodos de ganar dinero en internet...
[b][url=http://www.ganar-dinero-ya.com][img]http://www.ganar-dinero-ya.com/dinero.jpg[/img][/url]Te recomendamos entrar a [url=http://www.ganar-dinero-ya.com/]Ganar-dinero-ya.com[/url][url=http://www.ganar-dinero-ya.com][img]http://www.ganar-dinero-ya.com/dinero.jpg[/img][/url][/b]
Do you have copy writer for so good articles? If so please give me contacts, because this really rocks! :)
friends reunited dating [url=http://loveepicentre.com/]singles ski vacation in colorado[/url] philly singles scene http://loveepicentre.com/ horny woman dating
Post a Comment