Why not [1..5] == [1,2,3,4,5]?

Why not [1..5] == [1,2,3,4,5] ?

Why not [1..5].to_a == [1,2,3,4,5] ?

How to convert from [1..5] to [1,2,3,4,5] ?

+6
source share
2 answers

[1..5] is an array that has only one element, an object of range 1..5

[1..5].to_a is still [1..5]

(1..5).to_a [1,2,3,4,5]

+18
source

[1..5] is an array with one element - a range object, all attempts to iterate through it will fail. An array can have many kinds of objects. In my example above, I see a range as just a range and make any array out of it.

 1.9.3-p125 :008 > (1..5).to_a # Note regular parens. => [1, 2, 3, 4, 5] 1.9.3-p125 :009 > 

To more accurately say what you indicated - starting with [1..5] - you could do:

 1.9.3-p125 :013 > newarray = [] 1.9.3-p125 :014 > [1..5][0].each {|e| newarray << e} => 1..5 1.9.3-p125 :015 > newarray => [1, 2, 3, 4, 5] 1.9.3-p125 :016 > 
+2
source

Source: https://habr.com/ru/post/924983/


All Articles