What is inject doing here?

T

Todd Benson

Why does this not do what I expect?

irb(main):001:0> RUBY_VERSION
=> "1.9.2"
irb(main):002:0> (0..3).inject {|s, i| a = i%2 == 0 ? 1 : -1; p a}
-1
1
-1
=> -1

I would think the result should be

1
-1
1
-1
=> -1

Todd
 
M

Michael Edgar

The first two elements of the range are the first two elements to be =
used as arguments to
the inject block:

First, s =3D 0, i =3D 1:

a =3D 1 % 2 =3D=3D 0 ? 1 : -1; p a # a =3D -1

Then, s =3D -1, i =3D 2:

a =3D -1 % 2 =3D=3D 0 ? 1 : -1; p a # a =3D 1

Then, s =3D 1, i =3D 3:

a =3D 3 % 2 =3D=3D 0 ? 1 : -1; p a # a =3D -1

And the range is exhausted.

Michael Edgar
(e-mail address removed)
http://carboni.ca/
 
A

Adam Prescott

[Note: parts of this message were removed to make it a legal post.]

irb(main):002:0> (0..3).inject {|s, i| a = i%2 == 0 ? 1 : -1; p a}
-1
1
-1
=> -1

Why is this done using inject? s is never used in the block, but since `p a`
returns nil, s would be nil in every iteration after the first one.

(0..3).map { |n| n % 2 == 0 ? 1 : -1 }.each { |n| puts n }

You could of course just use each by itself:

(0..3).each do |n|
if n % 2 == 0
puts 1
else
puts -1
end
end
 
M

Michael Edgar

I'm pretty sure he's just trying to understand inject's behavior on =
ranges,
not looking for refactoring advice.

Also, on Ruby 1.9, Kernel#p returns its arguments.

Michael Edgar
(e-mail address removed)
http://carboni.ca/

 
A

Adam Prescott

[Note: parts of this message were removed to make it a legal post.]

Also, on Ruby 1.9, Kernel#p returns its arguments.

I forgot about that! :) I caught that one recently courtesy of JEG2.
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top