DEV Community

Ali Al Khawaja
Ali Al Khawaja

Posted on

How to create arrays in ruby using methods - AI generated

In Ruby, you can create arrays using various methods and techniques. Here are some common ways to create arrays in Ruby:

1. Using the Array Literal Syntax:

You can create an array by simply using square brackets [].

my_array = [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. Using the Array.new Method:

You can create an empty array or an array with a specified size using the Array.new method.

  • Empty Array:
  empty_array = Array.new
Enter fullscreen mode Exit fullscreen mode
  • Array with a Specified Size:
  array_with_size = Array.new(5)  # Creates an array with 5 `nil` elements
Enter fullscreen mode Exit fullscreen mode
  • Array with Default Values:
  array_with_default = Array.new(5, 0)  # Creates an array with 5 elements, all set to 0
Enter fullscreen mode Exit fullscreen mode

3. Using the Array#[] Method:

You can create an array using the Array#[] method, which can take multiple arguments.

my_array = Array[1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

4. Using the Array#new Method with a Block:

You can also create an array and populate it using a block.

squared_array = Array.new(5) { |i| (i + 1) ** 2 }  # Creates an array of squares: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

5. Using the Array#fill Method:

You can create an array and fill it with a specific value using the fill method.

filled_array = Array.new(5).fill(0)  # Creates an array with 5 elements, all set to 0
Enter fullscreen mode Exit fullscreen mode

6. Using the Array#concat Method:

You can create an array and then concatenate another array to it.

array1 = [1, 2, 3]
array2 = [4, 5, 6]
combined_array = array1.concat(array2)  # Results in [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

7. Using the Array#push Method:

You can start with an empty array and add elements to it using the push method.

my_array = []
my_array.push(1)
my_array.push(2)
my_array.push(3)  # Results in [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Summary:

These are some of the common methods to create arrays in Ruby. You can choose the method that best fits your needs based on whether you want to initialize an array with specific values, create an empty array, or populate an array dynamically.

Top comments (0)