Shift and unshift work off the left side of the array, just like the
similar commands do in Bash, Bourne Shell, and many other shells
(which is where, I believe, the naming came from). Pop and push work
on the right side of the array to do the same thing. So pop and push
work on the end with the highest index, where shift and unshift work
on the end with the lowest index.
​That's correct. The issue is that when operating on the left side of the
array (the "head"), you may have to copy all subsequent elements of the
array left or right one position. A clever implementation may implement
`shift` by incrementing the array pointer, thus relieving the need to move
each subsequent element left one position. However this isn't always
implemented, or even necessarily possible. Thus it's an implementation
detail (not specified by Ruby, and potentially different from
implementation to implementation).​
Shift was originally used as a
convenient way to process arguments off the function or script
argument list without having to state the identifier. No, I cannot
recall why that was a nice thing to do, but I think in earlier days it
turned out to be convenient.
​Back in the good old days function parameters were `push`ed onto the call
stack; however the parameter list is a (FIFO) queue, not a (LIFO) stack, so
to retrieve them in order you had to `shift` them off again.
While the details of the call stack are quite safely abstracted these days,
the paradigm of treating args/params as a list remains; especially in older
languages like Perl. Thus, in Perl, one can either splat the elements of
the argument list using parallel assignment {my ($a,$b,$c) = @_}, or shift
the elements off the args list as required {my $a=shift, $b=shift, $c=shift}
(N.B. if no list is passed to 'shift', it shifts from '@_' by default).​
As Ruby tries, more than most with success, to be congruent, you'll
probably find shift and unshift, as well as pop and push to be used
the same way with other containers or sequential data structures in
Ruby.
​Certainly it works on some list-like data structures (Array, Hash); it's
not generalised to Enumerable, though. I wouldn't say that Ruby tries to be
congruent; rather that it tries to make sense.
Cheers
···
On 28 July 2016 at 08:29, Xeno Campanoli <xeno.campanoli@gmail.com> wrote:
--
Matthew Kerwin
http://matthew.kerwin.net.au/