From: Jason Foreman Date: 2005-07-13T02:01:11+09:00 Subject: Re: Question: arrays v. ranges and *.each On 7/12/05, David Douthitt wrote: > The results of the following code just seem strange to me: > > print "\nTry 1:" > print [1..10].class, "\n" > [1..10].each { |x| print x, "\n" } > > print "\nTry 2:" > print [1..10].pop.class, "\n" > [1..10].pop.each { |x| print x, "\n" } > > I would have thought that either 1) try 1 would output a sequence of > numbers, and try 2 would result in an error (no such method > Integer#each); or, 2) try 1 would output a series of numbers and try 2 > would result in an error (no such method Range#pop). Perhaps - another > option would be 3) try 1 would result in '1..10' and try 2 would result > in something like '1..1' or an error? > > I'm confused... the .. operator does not output a series of numbers, but rather an instance of the class Range. Try 1 is an array with a single element, a Range object. Calling each on the array yields each element, in this case the single Range object, and you've output it to the console, which gives "1..10" which is how the Range responds to to_s. Try 2 is the same array. You pop the first element, which is the Range object, and call each, which iterates over the numbers represented by the range. Try this: (1..10).entries That gives you an array of all the elements represented by the Range. Jason