Ruby Array : Modification

chars = ["a", "b", "c"]
=> ["a", "b", "c"]

Insertion

chars.insert( 1, "d" )
=> ["a", "d", "b", "c"]

Modify one element

chars = ["a", "b", "c"]
chars[1] = "d"
=> "d"

chars
=> ["a", "d", "b"]

Modify multiple elements using range

chars = ["a", "b", "c"]
=> ["a", "b", "c"]

chars[1..2] = "d", "e"
=> ["d", "e"]

chars
=> ["a", "d", "e"]

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails