Array#inject with hash as initial, unexpected error

M

Matthew Moss

(On Mac OS X 10.4.5, Ruby 1.8.4)

Okay, so:
[1, 2, 3].inject(0) { |s, v| s +=3D v }
=3D> 6

and:
[1, 2, 3].inject([]) { |a, v| a << v**2 }
=3D> [1, 4, 9]

but:
[1, 2, 3].inject({}) { |h, v| h[v] =3D v**2 }
=3D> NoMethodError: undefined method `[]=3D' for 1:Fixnum


What gives?
I've tried replacing {} with Hash.new and a couple other variants without l=
uck.
 
T

Trevor Squires

Hey Matthew,

observe:

irb(main):001:0> [] << 100
=> [100]
irb(main):002:0> {}[:something] = 100
=> 100

The << operator on an array returns the array, while the [] operator
on a hash returns the value you assigned.

And the result of the last statement in your inject block will
replace the value for your memo on each iteration.

So... just make sure the last statement in your inject block is the
memo value you are accumulating:

[1,2,3].inject({}) { |memo, val| memo[val] = val**2; memo}

HTH,
Trevor
--
Trevor Squires
http://somethinglearned.com



(On Mac OS X 10.4.5, Ruby 1.8.4)

Okay, so:
[1, 2, 3].inject(0) { |s, v| s += v }
=> 6

and:
[1, 2, 3].inject([]) { |a, v| a << v**2 }
=> [1, 4, 9]

but:
[1, 2, 3].inject({}) { |h, v| h[v] = v**2 }
=> NoMethodError: undefined method `[]=' for 1:Fixnum


What gives?
I've tried replacing {} with Hash.new and a couple other variants
without luck.
 
M

Matthew Moss

Okay, I feel silly now. Thanks for the reminder on basic assignment
protocol. =3D)
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top