Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Does Ruby's Array#shift do?

Tags:

ruby

I am having a hard time understanding what the shift and unshift methods of the Array class do in Ruby. Can somebody help me understand what they do?

like image 282
ab217 Avatar asked Sep 15 '10 14:09

ab217


People also ask

What is array of hashes in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.

Is an array an object in Ruby?

What are array methods in Ruby? Array methods in Ruby are essentially objects that can store other objects. You can store any kind of object in an array. You can create an array by separating values by commas and enclosing your list with square brackets.


1 Answers

Looking at the Ruby Documentation

Array.shift removes the first element from the array and returns it

a = [1,2,3]  puts a.shift  => 1  puts a  => [2, 3]  

Unshift prepends the provided value to the front of the array, moving all other elements up one

a=%w[b c d]  => ["b", "c", "d"]  a.unshift("a")  => ["a", "b", "c", "d"]  
like image 179
Steve Weet Avatar answered Oct 03 '22 23:10

Steve Weet