What's the difference?

Hello @*,

irb(main):105:0> 10.times { d={}; puts d.object_id }
537970544
537969634
537969504
537969404
537969354
537969334
537969304
537969274
537969244
537969184
=> 10
irb(main):106:0>

10 different Hash objects are constructed and their id's are printed out
why doesn't the following do the same?

irb(main):106:0> 10.times { puts {}.object_id }

=> 10
irb(main):107:0>

I copied & pasted the above code
mond:/pool/PROG/ruby # irb -v
irb 0.9(02/07/03)

I am in the learning phase so I experement a lot

thx, Daniel

Daniel Schüle wrote:

Hello @*,

irb(main):105:0> 10.times { d={}; puts d.object_id }
537970544
537969634
537969504
537969404
537969354
537969334
537969304
537969274
537969244
537969184
=> 10
irb(main):106:0>

10 different Hash objects are constructed and their id's are printed out
why doesn't the following do the same?

irb(main):106:0> 10.times { puts {}.object_id }

=> 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
=> 10

Why does this funny association happen? Ruby thinks the {} without
parens is a block, not a hash:

irb(main):004:0> puts {}

=> nil
irb(main):005:0> puts do end

=> nil
irb(main):006:0> puts {exit}

=> nil

The block is silently ignored by ruby.

···

--
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Why does this funny association happen? Ruby thinks the {} without
parens is a block, not a hash:

irb(main):004:0> puts {}

=> nil
irb(main):005:0> puts do end

=> nil
irb(main):006:0> puts {exit}

=> nil

The block is silently ignored by ruby.

thank you for this explanation, I think I got it.
if a function doesn't expect a block parameter
but gets one, then this block is ignored

def foo; end
foo {exit} => nil
foo { puts "hello" } => nil

and puts is not supposed to take a block as parameter

Regards, Daniel

Daniel Schüle

thank you for this explanation, I think I got it.
if a function doesn't expect a block parameter
but gets one, then this block is ignored

def foo; end
foo {exit} => nil
foo { puts "hello" } => nil

and puts is not supposed to take a block as parameter

That's right. Your method foo also ignores any given block; it's the default
behaviour.

p {} # a block
p({}) # a hash

Cheers,
Dave