Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

Short Notes – Ruby Arrays- Insert, Append, length, Index, Removed

scmuser created the topic: Short Notes – Ruby Arrays- Insert, Append, length, Index, Removed

Short Notes – Ruby Arrays- Insert, Append, length, Index, Removed

Create a Ruby Array

[code language=”css”]
letters = Array.new
letters = []
letters = Array.new()
letters =
letters = Array.new(3) ( Define how many elements you array would be)
letters = Array.new(3, ‘me rocks’) (Define each element with default values)
[/code]

Accessing Elements

[code language=”css”]
letters[0] – accessing First element
letters[-1] – Accessing last element
letters[-2]
[/code]

Inserting/Adding elements

[code language=”css”]
letters = Array.new() OUTPUT = [“a”, “b”, “c”]
letters.insert(0, 1) OUTPUT [1, “a”, “b”, “c”, “d”]
letters.insert(-1, ‘d’) OUTPUT [1, “a”, “b”, “c”, “d”]
letters << ‘e’ OUTPUT [1, “a”, “b”, “c”, “d”, “e”]
letters.push(‘f’) OUTPUT [1, “a”, “b”, “c”, “d”, “e”, “f”]
[/code]

Removing Elements

[code language=”css”]
letters.pop – Remove the last elements
letters.delete_at(2) – Delete the element of particular index
[/code]

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x