problem with ruby19's Hash behavior

A

Aaron

see the following codes pls, I wonder if this's a intent or a bug. For me the first line sounds better having same result with the later line
[1].inject(Hash.new {[]}){ |result, i| result[:mem] << i; result } => {}
[1].inject(Hash.new {[]}){ |result, i| result[:mem] <<= i; result }
=> {:mem=>[1]}

P.S. coding with ruby 1.9.2p180 atm
 
R

Roger Braun

Hi Aaron

2011/4/25 Aaron said:
see the following codes pls, I wonder if this's a intent or a bug. For me=
the first line sounds better having same result with the later line
[1].inject(Hash.new {[]}){ |result, i| result[:mem] << i; =C2=A0 result=
}
=3D> {}
[1].inject(Hash.new {[]}){ |result, i| result[:mem] <<=3D i; result }
=3D> {:mem=3D>[1]}

It's the expected behaviour. See
http://ruby-doc.org/core/classes/Hash.html#M000718.

"If a block is specified, it will be called with the hash object and
the key, and should return the default value. It is the block=E2=80=98s
responsibility to store the value in the hash if required."

[1].inject(Hash.new {|h,k| h[k] =3D Array.new}){ |result, i|
result[:mem] << i; result }
=3D> {:mem=3D>[1]}

--=20
Roger Braun
rbraun.net | humoralpathologie.de
 
R

Roy Zuo

Hi,

I still cannot understand.

In the first example, result[:mem] should be [ ] before "result[:mem] << i" is
executed. Afterwards it should be [1], and the return value should be {:mem =>
[1]}.

In the second example, what does "<<=" stand for?

Roy

Hi Aaron

2011/4/25 Aaron said:
see the following codes pls, I wonder if this's a intent or a bug. For me the first line sounds better having same result with the later line
[1].inject(Hash.new {[]}){ |result, i| result[:mem] << i;   result } => {}
[1].inject(Hash.new {[]}){ |result, i| result[:mem] <<= i; result }
=> {:mem=>[1]}

It's the expected behaviour. See
http://ruby-doc.org/core/classes/Hash.html#M000718.

"If a block is specified, it will be called with the hash object and
the key, and should return the default value. It is the block‘s
responsibility to store the value in the hash if required."

[1].inject(Hash.new {|h,k| h[k] = Array.new}){ |result, i|
result[:mem] << i; result }
=> {:mem=>[1]}

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,368
Latest member
EwanMacvit

Latest Threads

Top