Forum: Ruby Re: Dice Roller (#61) We don't need no steenking leexer/pars

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kroeger, Simon (ext) (Guest)
on 2006-01-09 16:20
(Received via mailing list)
Hi,

first: you don't need the 'to_a'

second:
---------------------------------------
(0..5).inject{|x,y| print y, ' '}
puts

(1..5).inject(0){|x,y| print y, ' '}
puts
---------------------------------------
output:

1 2 3 4 5
1 2 3 4 5

If you provide no parameter to inject it will give
you the first item of the enumerable as x.

cheers

Simon
Paul N. (Guest)
on 2006-01-09 18:03
(Received via mailing list)
On 1/9/06, Kroeger, Simon (ext) <removed_email_address@domain.invalid> wrote:
> Hi,
>
> first: you don't need the 'to_a'
Excellent!  Less typing, and more importantly, less to parse when
reading.

> 1 2 3 4 5
> 1 2 3 4 5
>
> If you provide no parameter to inject it will give
> you the first item of the enumerable as x.
>

That is true when you are using that first item, but for the dice
roll, we do not want the value of x in our accumulator, we are just
using length of the range to control the number of rolls.

In fact, maybe my original version was not a bug after all.  Look at
these simplified statements:

irb(main):041:0> (0..2).inject{|x,y|x+2}
=> 4
irb(main):042:0> (1..2).inject(0){|x,y|x+2}
=> 4


I looks like the first example above walks through [0,1,2] and calls
the x + 2 code block two times:
first time x=0 and y = 1, returns 2
second time x = 2 (accumulated from last time) and y=2, returns 4

The second one takes [1,2] and also calls the x + 2 code block twice.
first time x=0 (this time from the initialization value), y = 1, returns
2
second time x=2 and y = 2, returns 4

Ruby doc says this is because the  "second form uses the first element
of the collection as a the initial value (and skips that element while
iterating)."

I think that answers Greg's question too.
This topic is locked and can not be replied to.