From: Glenn Jackman on 11 Sep 2009 15:22 At 2009-09-11 02:07PM, "7stud --" wrote: > Glenn Jackman wrote: > > While I thank you for takking the time, I can't say I'm enlightened by > > your explanation. What's the real difference between the blocks > > > > bar = products.inject(Hash.new([])) {|h,p| h[p.category] << p; h} > > baz = products.inject(Hash.new([])) {|h,p| h[p.category] += [p]; h} > > > > Is it because += explicitly assigns a new object to the hash key? > > Yes. When the key doesn't exist the first line is equivalent to: > > bar = products.inject(Hash.new([])) {|h,p| [] << p; h} > > which does nothing to the hash--all it does is append p to an empty > array, and then the empty array is discarded. As we've seen, it's not discarded: it's kept for h's reference: products = [[1,2],[3,4],[1,5]] foo = products.inject(Hash.new([])) {|h,(a,b)| h[a] << b; h} # => {} foo[:unknown] # => [2, 4, 5] -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous
From: 7stud -- on 11 Sep 2009 17:25 Glenn Jackman wrote: > At 2009-09-11 02:07PM, "7stud --" wrote: >> >> bar = products.inject(Hash.new([])) {|h,p| [] << p; h} >> >> which does nothing to the hash--all it does is append p to an empty >> array, and then the empty array is discarded. > > As we've seen, it's not discarded: it's kept for h's reference: > > products = [[1,2],[3,4],[1,5]] > foo = products.inject(Hash.new([])) {|h,(a,b)| h[a] << b; h} # => {} > foo[:unknown] # => [2, 4, 5] ...and this is a lie too: > If you access a non-existent key, say h["A"], then that line is > equivalent to > baz = products.inject(Hash.new([])) {|h,p| h["A"] = [] + [p]; h} You asked for lies. I gave them to you. -- Posted via http://www.ruby-forum.com/.
First
|
Prev
|
Pages: 1 2 3 Prev: iconv "\n" (Iconv::InvalidCharacter) Next: [QUIZ] URL Shenanigans (#220) |