Inserting and Moving elements inside Ruby Array

Here's is an array with 5 elements
2.1.2 :001 > arr = ["a", "b", "c", "d", "e"]
 => ["a", "b", "c", "d", "e"] 
Lets look at few different cases
  1. Insert a new element at starting position
      Using unshift
      2.1.2 :002 > arr.unshift("f")
       => ["f", "a", "b", "c", "d", "e"] 
      
      Using insert
      2.1.2 :005 > arr.insert(0, "f")
       => ["f", "a", "b", "c", "d", "e"]
      
      In the above example 0 is the position(index)
  2. Move existing element from one position to another


    The element in this case is "e"
    Using uniq to show only unique elements
    2.1.2 :009 > arr.insert(0, "e").uniq
     => ["e", "a", "b", "c", "d"] 
    
    With uniq we are only showing unique records but the element is listed twice in actual array
    Another option is deleting the element from old position
    2.1.2 :012 > arr.insert(0, arr.delete_at(arr.index("e")))
     => ["e", "a", "b", "c", "d"] 
    We are using "index" to determine the old position and delete_at to delete the element from the old position

Comments

Popular posts from this blog

Difference between Validations, Callbacks and Observers