Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is [....] in Ruby? [duplicate]

Tags:

object

ruby

I ended up accidentally doing the equivalent of this in Ruby the other night:

a = *1..5  # => [1, 2, 3, 4, 5]
a << a
a          # => [1, 2, 3, 4, 5, [...]]
a.last     # => [1, 2, 3, 4, 5, [...]]

What is [...] and what can I do with it?

like image 524
Johan Svensson Avatar asked Feb 15 '13 13:02

Johan Svensson


People also ask

What does DUP do in Ruby?

The default Ruby implementation of the #dup method allows you to add a special initializer to your object that is only called when an object is initialized via the #dup method. These methods are: initialize_copy.

How do you copy an object in Ruby?

Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class. What this does exactly is dependent on the class.


1 Answers

It's just the way Array.inspect displays recursive arrays. The last Element of a is a itself. If a where displayed after 5, inspect would end up in an endless loop:

[1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [...]]]]]
like image 172
Torsten Robitzki Avatar answered Oct 20 '22 23:10

Torsten Robitzki