J
Joel VanderWerf
Daniel said:Hello @*,
=20
irb(main):105:0> 10.times { d=3D{}; puts d.object_id }
537970544
537969634
537969504
537969404
537969354
537969334
537969304
537969274
537969244
537969184
=3D> 10
irb(main):106:0>
=20
10 different Hash objects are constructed and their id's are printed ou= t
why doesn't the following do the same?
=20
irb(main):106:0> 10.times { puts {}.object_id }
=20
=20
=20
=20
=20
=20
=20
=20
=20
=20
=3D> 10
irb(main):107:0>
Ruby's parser associates the second line like this:
irb(main):001:0> 10.times { (puts {}).object_id }
Which does a "puts {}" ten times, and prints 10 blank lines. the
#object_id method is called on the return value of puts (which is nil)
and is never printed.
But:
irb(main):002:0> 10.times { puts({}.object_id) }
-606176002
-606176022
-606176042
-606176072
-606176092
-606176112
-606176132
-606176162
-606176182
-606176202
=3D> 10
Why does this funny association happen? Ruby thinks the {} without
parens is a block, not a hash:
irb(main):004:0> puts {}
=3D> nil
irb(main):005:0> puts do end
=3D> nil
irb(main):006:0> puts {exit}
=3D> nil
The block is silently ignored by ruby.
--=20
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407