Create array of empty subarrays in Ruby

I want to create an array of n number of distinct empty subarrays.

Is this the best way?

Array.new(n){ [] }

It was as follows, but I modified after reading comments:

Array.new(n){ |_| [] }

I tried:

Array.new(n, [])

but it creates an array with all the subarrays being the same object, which I do not want.

Array.new(n){ [] }is totally fine! The block ensures that a new instance of Array is created n times. As you pointed out, you would otherwise reference the same object (instance of Array) n times.

Basic Guide to Creating Arrays in Ruby, variables if you were to read a list of things from the keyboard or from a file. Ruby Two Dimensional Array: In this tutorial, we are going to learn about two-dimensional array in Ruby programming language, creating a two-dimensional array, accessing array elements and accessing subarrays, etc. Submitted by Hrithik Chandra Prasad, on December 25, 2019 Ruby Two Dimensional Array

All the proposed method to get this array [[], [], [],...] works fine:

Array.new(n, []) # the best, 20 times faster
Array.new(n){ [] }
n.times.map { [] }

The first is the fastest, so the best, but works strangely (see next).

it created an array with all the sub arrays being the same object

If i get the point, you mean that whit the methods described happens what follows:

a = Array.new(5, [])
p a # => [[], [], [], [], [], [], [], [], [], []]
p a.map { |e| e.object_id} # => [70189488740180, 70189488740180, 70189488740180, 70189488740180, 70189488740180]]

The object is the same, so if you try to fill subarrays with values, all of the subarrays assume the same value (replication):

a[0][0] = 10
p a # => [[10], [10], [10], [10], [10]]

To avoid this don't pass a default value, but map to empty array instead:

a = Array.new(5).map{ |e| [] }
p a # => [[], [], [], [], []]

Or pass the block

a = Array.new(5){ [] }
a = 5.times.map { [] }

Now each subarray is an independent object:

p a.map { |e| e.object_id} # => [70253023825640, 70253023825620, 70253023825600, 70253023825580, 70253023825560]

And if you insert some values there is no replication:

a[0][0] = 10
a[1][0] = 20
p a # => [[10], [20], [], [], []]

How To Work with Arrays in Ruby, How do you create an array of objects in Ruby? Creating Empty Arrays. You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.

Please try this. It work for me.

  n = 15
  arr = Array.new(n)
  arr.map!{ |x| x = [] }

Now, putting value in the array.

arr[0][0] = 10 
arr[5][0] = 50
p arr # => [[10], [], [], [], [], [50], [], [], [], [], [], [], [], [], []]

4.4.2 Nested hashes, is Hammerhead , which is indexed at 0 . Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array --- that is, an index of -1 indicates the last element of the array,

class Array - Documentation for Ruby 2.0.0, I want to create an array of n number of distinct empty subarrays. Is this the best way? Array.new(n){ [] }. It was as follows, but I modified after  To create an array in a Ruby program, use square brackets: ( [] ), and separate the values you want to store with commas. For example, create an array of sharks and assign it to a variable, like this: sharks = ["Hammerhead", "Great White", "Tiger"] You can print out an entire array with the print statment, which will display the array’s contents:

Ruby - Arrays, To create an array with separate objects a block can be passed instead. This method is In the first form, if no arguments are sent, the new array will be empty​. Returns nil if no modifications were made (i.e., the array contains no subarrays.). Minimum number of swaps required to sort an array of first N number; Count of subarrays of an Array having all unique digits; Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM) Longest alternating subsequence in terms of positive and negative integers; Count of subarrays having exactly K distinct elements

Ruby Arrays Cheat Sheet, Ruby arrays grow automatically while adding elements to them. Creating Arrays. There are many ways to create or initialize an array. One way is with the new  Returns a new array. In the first form, if no arguments are sent, the new array will be empty. When a size and an optional default are sent, an array is created with size copies of default. Take notice that all elements will reference the same object default.

Comments
  • Another way: n.times.map { |_| [] }
  • Slightly more succinct: Array.new(n){[]}
  • Smells like XY problem. Maybe you need Matrix?
  • @Neddy: Note also that if you have subarrays - empty or not - the "parent" array is not empty.
  • "an empty array of empty sub arrays" is a self-contradiction. An empty array contains nothing.
  • This is what I am going with, I wasn't sure if there was a more correct way to do this, but it appears not. Thank you!
  • Why use map when you can simply pass a block to new as shown in the beginning?
  • @Stefan Ooops! Edit. Thanks. But I'm still not sure about what's the OP issue.
  • The original question was "is there a better way than Array.new(n){ |_| [] }", so the OP probably just wanted to know if there is a shorthand syntax to create an array of empty arrays.
  • The assignment in x = [] is superfluous, you just need arr.map!{ [] }. Which is merely Array.new(n) { [] } on two lines.