In Ruby, to include products to the begin of a variety, we can just utilize the Ruby unshift technique. The unshift technique will certainly include a component to the begin of the variety.

 num_array = [1, 2, 3]
num_array. unshift( 4 );
print num_array
#Output:
[4, 1, 2, 3]

We can additionally utilize the unshift technique to include numerous aspects to a variety.

 num_array = [1, 2, 3]
num_array. unshift( 4,5);.
print num_array.
#Output:.
[4, 5, 1, 2, 3]

When dealing with collections of information in Ruby, the capacity to quickly include products or alter the collection is necessary. One such situation where we might intend to change a collection is if we intend to include aspects to a variety in Ruby. To include a thing to a variety in Ruby, we can utilize the unshift technique. The unshift technique will certainly include a component or aspects to the begin of the variety.

Below reveals an easy instance of just how we can utilize the unshift technique to include a thing to the begin of a variety in Ruby.

 string_array = ["red","yellow","black","blue"];.
string_array. unshift(" orange").
print string_array.
#Output:.
["orange", "red", "yellow", "black", "blue"]

Adding Several Things to the Begin of a Selection in Ruby

If we intend to include numerous products to a variety in Ruby, after that we might once more utilize the unshift technique as well as consist of numerous products in it. Below is the code to include numerous aspects to a variety utilizing the unshift technique in Ruby.

 colors_array = ["red","yellow","black","blue"];.
colors_array. unshift(" orange"," pink"," purple").
print colors_array.
#Output:.
["orange", "pink", "purple", "red", "yellow", "black", "blue"]

Using the prepend Technique to Include Things to the Begin of a Selection in Ruby

Another technique we can utilize to include products to the begin of a variety is the Ruby prepend technique. The prepend technique operates in similarly as the unshift technique, as well as we can include one or numerous products to a variety utilizing it. Allow’s see an instance of this technique.

 colors_array = ["red","yellow","black","blue"];.
colors_array. prepend(" orange").
print colors_array.
#Output:.
["orange", "red", "yellow", "black", "blue"]

And right here is an instance of including numerous products to the begin of a variety utilizing the prepend technique in Ruby.

 colors_array = ["red","yellow","black","blue"];.
colors_array. prepend(" orange"," pink"," purple").
print colors_array.
#Output:.
["orange", "pink", "purple", "red", "yellow", "black", "blue"]

Hopefully this post has actually worked for you to discover just how to utilize the Ruby unshift technique.



Source link .