Xavier Noria
11/12/2006 8:22:00 PM
On Nov 12, 2006, at 8:58 PM, Tom Pollard wrote:
> On Nov 12, 2006, at 2:40 PM, Paul Lutus wrote:
>> Let's say we have an instance variable named "hash" that we are
>> not sure has
>> been initialized at runtime, and we want to create a new hash
>> where there
>> is none, but only then. Add this line:
>>
>> hash ||= {}
>>
>> Means "if 'hash' is a hash, do nothing, otherwise create a hash".
>
> Strictly speaking, doesn't it mean "if 'hash' is nil (or false),
> assign to a newly created empty hash"? You're not testing whether
> it's actually a hash already. Also, maybe it's worth reminding the
> OP that an empty hash is not treated as 'false' in a logical
> expression in Ruby, as it would be in Perl. So, if you were to
> repeatedly evaluate
>
> hash ||= {}
>
> you'd only create a new Hash the first time. In Perl, on the other
> hand, repeatedly evaluating the similar expression
>
> $hashref ||= {}
>
> would create and assign a new hash repeatedly, until some hash
> element was assigned.
Well, in that case there's only one assignment indeed, because a
hashref is true in Perl as well:
$ perl -wle 'do {$h ||= {}; print $h} for 1..3'
HASH(0x1800e8c)
HASH(0x1800e8c)
HASH(0x1800e8c)
-- fxn