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?
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.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With