I have an array. I need to keep everything except the element at index 0. My brain is fried at this point. I've been programming all day. Any help would be amazing. Thank you!
4 Answers
Use the Array#shift method, it does exactly what you want:
a = [1, 2, 3]
a.shift # => 1
a # => [2, 3]
3 Comments
shift or unshift removes items from the array, try dropping the "f" from the name. :)how about slice!
a = [ "a", "b", "c" ]
a.slice!(0) #=> "a"
a #=> ["b", "c"]
http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-slice-21
Comments
Depending on how what will be done with the result (an array with the first element removed) there are different ways to get the result and how it will be used may affect the choice.
One way changes the original array to a new array with the first element removed by applying a method, ignoring the result of that method and achieving the desired outcome due to the side effect of the applied method. The OP accepted an answer that did this (which implies it worked in his case):
a = [ "a", "b", "c" ]
a.shift #=> "a"
a #=> ["b", "c"]
That works well if you want the resulting array preserved but it your need is to drop some method into the middle of a chain of existing methods in order to "get rid of that first array element." But, in my case I had an array where the first element was a heading line produced by a system command followed by several lines of the output from that command, one in each array element and was modifying the lines to achieve my desired result when I realized that the header line needed to be removed since, being of a different form from the remaining lines, it wasn't handled correctly and wasn't needed. My original line of code looked something like this (where again, a is the array):
puts a.method1.method2.method3.method4
and I wanted to do this:
puts a.method1.method2.removeFirstElement.method3.method4
One way to do this by using slice was shown in a different answer though it wasn't made clear how it could be better in some cases than the accepted answer:
puts a.method1.method2.slice(1..-1).method3.method4
If I used the accepted answer I would have to do something like this:
temp = a.method1.method2
temp.shift
puts temp.method3.method4
Besides the need to revise the original code structure (though there are pros and cons to that depending on what's being done), it's necessary to create a new temporary object ('temp') just to get to the result.
It's good to know that where we are heading often has a definite effect on how to get there.
(I'll note that I would almost prefer the use of slice!(0) in place of shift to actually change the array since the exclamation point makes it clear that the array is being changed; the shift method doesn't conform to the current suggestion of adding an exclamation point to methods that will alter an object. But, alas, I'd probably use shift anyway to avoid the clutter of the (0).)