Peña, Botp wrote:
> From: Chris Shea [mailto:cmshea / gmail.com]
> # It's better to think of x ||= "ruby" as x || x = "ruby".
> #
> # --
> # h = Hash.new('default value')
> #
> # h[:test] ||= 'assigned value'
> # h # => {}
> #
> # # same as:
> # h[:test] || h[:test] = 'assigned value'
> # h # => {}
> #
> # # not:
> # h[:test] = h[:test] || 'assigned value'
> # h # => {:test=>"default value"}
> 
> 
> i'd say that's a bug in design (unless x+=1 is now x+x=1 ;)
> 
> kind regards -botp

Not at all. Rather, this is just a subtle misunderstanding of how hash 
is implemented. Consider the following:

>> h = Hash.new
=> {}
>> h[:test] ||= 'testing without default'
=> "testing without default"
>> h
=> {:test=>"testing without default"}
>> h = Hash.new('default value')
=> {}
>> h[:test] ||= 'testing with default'
=> "default value"
>> h
=> {}

The only reason that Chris' example behaves like "x || x = stuff" is 
because he's defined a default value for the hash. If you set a default 
value, than you'll never have a keyed value be empty (i.e. nil). 
Consider further:

>> h = Hash.new
=> {}
>> puts 'empty' unless h[:test]
empty
=> nil
>> h = Hash.new('default value')
=> {}
>> puts 'empty' unless h[:test]
=> nil
>> 

I think the confusion is that, in Chris' example, there's no assignment, 
so the hash only holds the default value temporarily (i.e. just long 
enough to not evaluate to nil or false).
-- 
Posted via http://www.ruby-forum.com/.