AlexG
10/13/2006 1:16:00 AM
John Gabriele wrote:
> On 10/12/06, Booker C. Bense
> <bbense+comp.lang.ruby.Oct.12.06@telemark.slac.stanford.edu> wrote:
> > In article <65e0bb520610121433u151b89d9y1d757621bc4d41d3@mail.gmail.com>,
> > John Gabriele <jmg3000@gmail.com> wrote:
> > [snip]
> > >
> > >So, back to Ruby, I believe that the rhs of the following statement is
> > >an "Array expression":
> > >
> > >irb(main):001:0> foo = ['a','bee','sea']
> > >=> ["a", "bee", "sea"]
> > >
> > >but, what kind of expression is the rhs of the following:
> > >
> > >irb(main):002:0> bar = 'dee', 'ee', 'eff'
> > >=> ["dee", "ee", "eff"]
> > >
> > >?
> >
> > One of the nice things about Ruby is that you can always ask it
> > what it thinks.
> >
> > irb(main):090: bar.class
> > => Array
> > irb(main):010:0> bar.methods
> > => ["respond_to?", "index", "select", "<<", "to_a", "delete_if",
> > "slice", "&", "type", "each_index", "length",
> > [snip]
>
> Right. I see that bar is an Array, but I what I meant was, what kind
> of expression is that comma-separated thingy on the right hand side
> (when I made the assignment to bar)? Evidently, the answer seems to be
> that ruby is allowing a little bit of extra syntactic sugar to make it
> so I don't have to type those square brackets.
>
> > >
> > >Incidentally, I also note that this one -- although performing
> > >parallel assignment -- also happens to be generating an Array value:
> > >
> > >irb(main):003:0> zz = ( a, b, c = 'gee', 'aitch', 'aye' )
> > >=> ["gee", "aitch", "aye"]
> > >
> > >irb(main):004:0> zz
> > >=> ["gee", "aitch", "aye"]
> > >
> > >According to irb, the Array gets generated even if you leave off the
> > >"zz =" and the parentheses. Seems like extra work for the interpreter
> > >to go through (making that Array), just to do a parallel assignment,
> > >no?
> >
> > It's not making an Array, it's making a reference to an existing
> > object.
>
> Huh? irb seems to be clearly showing an Array. I'm thinking it's like
> in C++ where you have this little short-lived temporary object. It
> seems like it's an extra step for the interpreter to bother making
> that extra temporary -- I'd think it could've just done the assignment
> to a, b, and c and be done with it.
>
> ---John
Someone with better understanding of Ruby internals will need to
confirm this because I may well be wrong, but I think you are correct.
eval.c creates a temporary array out of the right-hand side (in the
svalue_to_mrhs function I think). Page 91 of the Pickaxe (2nd Ed)
explains this a little more. Whether or not optimising the Array away
is possible or desirable is another question. Unless you are doing some
pretty insane parallel assignment I wouldn't have thought it makes any
practical difference.
Alex Gutteridge