How to add/remove elements to Array in Ruby?

To add or remove lements to/from array in Ruby we have different methhods.

Array.push method to add elements into Array

Example

# creating an empty array

arr1 = Array.new()

 

# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n Addding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;

Output

another string
 
Addding New Element
another string
2

 

Array.pop method to remove lement from array

pop() will remove one by one element from Array.

Example

# creating an empty array

arr1 = Array.new()

# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n adding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;

arr1.pop();

puts "\n remove last Element"

puts arr1;

arr1.pop();

puts "\n remove last Element"

puts arr1;

 

Output

another string

 adding New Element
another string
2

 remove last Element
another string

 remove last Element

 

How to delete specifi index Element from Array in Ruby?

Ruby Array has method delete_at() to delete element from specified index.

Example

# creating an empty array

arr1 = Array.new()

# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n adding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;

arr1.delete_at(1);

puts "\n delete element at index 1"

puts arr1;

 

Output

another string

 adding New Element
another string
2

 delete element at index 1
another string

 


Flutter Questions

Android Questions

Python Questions

Java Questions