From: Robert Klemme Date: 2011-01-12T00:30:44+09:00 Subject: Re: Parallel Assignments and Elegance/Complexity Ratio. On Tue, Jan 11, 2011 at 3:29 PM, 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? Just today I used def []=(*idx, val) index_check(idx) @data[idx] = val end https://gist.github.com/772827 See also thread "Nooby question : multidimensional arrays.". I find the pattern matching _very_ elegant. This also comes in handy in situations like this: irb(main):001:0> a = Array.new(10) { [rand(10), rand(10)] } => [[2, 3], [7, 8], [4, 0], [4, 6], [5, 2], [9, 9], [4, 2], [8, 5], [2, 6], [5, 9]] irb(main):002:0> a.sort {|(a1,a2),(b1,b2)| x = a2 <=> b2; x == 0 ? a1 <=> b1 : x} => [[4, 0], [4, 2], [5, 2], [2, 3], [8, 5], [2, 6], [4, 6], [7, 8], [5, 9], [9, 9]] Although in this particular case you could also use irb(main):004:0> a.sort_by {|arr| arr.reverse} => [[4, 0], [4, 2], [5, 2], [2, 3], [8, 5], [2, 6], [4, 6], [7, 8], [5, 9], [9, 9]] irb(main):005:0> a.sort_by {|x, y| [y, x]} => [[4, 0], [4, 2], [5, 2], [2, 3], [8, 5], [2, 6], [4, 6], [7, 8], [5, 9], [9, 9]] Generally I'd say I don't use it overly often but when I use it it is really handy. With #inject it's also useful if you iterate through a collection of Arrays of known equal length: irb(main):006:0> a.inject(0) {|s,(x,y)| s + x + y} => 100 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/