From: Marnen Laibow-Koser on
Eva wrote:
> Hi,
>
> Please take a look at below:
>
> def mytest
> return [1..10]
> end
>
> x = mytest
> x.each do |c| puts c end
>
>
> this works not as I expected.
> I want the output of:
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> 10
>
>
> But if I change return [1..10] to return 1..10 it will work.
> So what's the difference between 1..10 and [1..10]?

1..10 is a Range. [1..10] is an Array with one element (that happens to
be a Range, but that's irrelevant). Range#each returns each element in
the range, so you get 1, 2, 3, etc. Array#each likewise returns each
element in the array -- but your array only has one element, the Range
object itself!

If you want an Array with the elements 1 to 10, you need something like
(1..10).to_a .


> THanks.

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
marnen(a)marnen.org
--
Posted via http://www.ruby-forum.com/.