Hi --

On Thu, 6 Oct 2005 waterbowl / gmail.com wrote:

> Is it possible to write a method in Ruby that acts like pop does in
> Lisp? Array#shift is an obvious candidate but there's a difference. For
> example:
>
> Ruby:
>
> irb(main):001:0> x = [[:a, :b], :c]
> => [[:a, :b], :c]
> irb(main):002:0> y = x.first
> => [:a, :b]
> irb(main):003:0> y.shift
> => :a
> irb(main):004:0> y
> => [:b]
> irb(main):005:0> x
> => [[:b], :c]
> irb(main):006:0>
>
> Lisp:
>
> [2]> (setq x '((a b) c))
> ((A B) C)
> [3]> (setq y (car x))
> (A B)
> [4]> (pop y)
> A
> [5]> y
> (B)
> [6]> x
> ((A B) C)
>
> y.shift causes x to be modified whereas Lisp's (pop y) does not modify
> x.
>
> If Ruby had macros we could use them to define pop. Given that it does
> not, is there some other way to define a method to do this?

If you want to alter an array that's like x[0], but isn't x[0], you
can use dup:

   y = x[0].dup
   y.shift


David

-- 
David A. Black
dblack / wobblini.net