From: Josh Cheek Date: 2011-01-12T04:58:16+09:00 Subject: Re: Parallel Assignments and Elegance/Complexity Ratio. --001636c5a30e3238a1049997811f Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jan 11, 2011 at 8:29 AM, Kedar Mhaswade wrote: > In SICP, I read that "Programs should be written for people to read, and > only incidentally for machines to execute". > > While reading David/Matz book, I stumbled upon parallel assignments and > I thought the language was trying to be too flexible (adding complexity, > at least for a newcomer). My head soon started > spinning (when it reached a, (b, (c,d)) = 1, [2, [3, 4]] I was > exhausted). > > My experience is recorded here: > > https://docs1.google.com/document/d/1zpHvfO4be3UvjaxU7L5gEPXFMENcMmEz9qqIcecEzOg/edit?hl=en# > > Summary is, I should only spend time learning > - x, y, z = 1, 2, 3 (# => x=1, y=1, z=3), and > - x, y = y, x (# => swap x and y) > > I gather that this might be a matter of taste and style, but are other > variants used by community? > > Thank you, > Kedar > > -- > Posted via http://www.ruby-forum.com/. > > I don't use it very often, but when I do, it usually makes an elegant solution. I think part of the reason it doesn't seem that way is because you are playing with it in too sterile of an environment. For example, you rate "x, (y, (z, a))=[1, [2, [3, 4]]]" as lowest, suggesting it is equivalent to "x=1;y=2;z=3;a=4" but this is not true. If you are actually assigning with literals, you would, of course, use the equivalent way, but if your data comes in as nested arrays, then you can't assign like that, instead you have to do something like this: def parallel(values) x, (y, (z, a))=values [x,y,z,a] end def alternative(values) x = values.shift values = values.shift y = values.shift values = values.shift z = values.shift a = values.shift [x,y,z,a] end parallel [1, [2, [3, 4]]] # => [1, 2, 3, 4] alternative [1, [2, [3, 4]]] # => [1, 2, 3, 4] Now, I don't normally store data like that, so I haven't ever done anything quite that fancy, but I use arrays on the RHS on occasion. It might look something like this (though I don't normally store my data like this, either -- it's really hard to think of a decent example!). $stdin = DATA while input = gets name , num = input.split puts "#{name.capitalize}'s favourite number is #{num}" end __END__ josh 12 bill 42 sally 13 ned 99 clara 1000000 The alternative of name , num = input.split is values = input.split name = values.shift num = values I consider the former to be much more elegant as it avoids a temporary variable. --001636c5a30e3238a1049997811f--