how to make a new array ruby
To create a new array in Ruby, follow these steps:
Start by declaring an empty array variable using the square brackets syntax. For example:
ruby new_array = []
You can also create a new array with initial values by listing the values inside the square brackets, separated by commas. For example:
ruby new_array = [1, 2, 3, 4, 5]
If you have an existing array and want to create a new array based on it, you can use the
dup
method to create a shallow copy of the original array. For example:ruby original_array = [1, 2, 3, 4, 5] new_array = original_array.dup
Another way to create a new array is by using the
Array.new
method. You can pass the desired size of the array as an argument, and optionally specify a default value for all the elements. For example:ruby new_array = Array.new(3) # creates an array with three elements, all set to nil new_array = Array.new(3, 0) # creates an array with three elements, all set to 0
Additionally, you can use the
Array
class's instance methods to create new arrays. Some commonly used methods includeflatten
,compact
, anduniq
. These methods perform specific operations on the original array and return a new array as a result.
Remember to assign the newly created array to a variable so that you can access and manipulate its elements later in your code.