From: Kedar Mhaswade Date: 2011-01-12T03:54:00+09:00 Subject: Re: Parallel Assignments and Elegance/Complexity Ratio. Robert Klemme wrote in post #973945: > On Tue, Jan 11, 2011 at 3:29 PM, Kedar Mhaswade > wrote: >> > 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: Maybe I am not understanding it, but I thought that elegance is because of splat operator (which I am sure I like). My gripe is about various forms of parallel assignment and semantic/syntactic complexity because of that. Or are you saying that once you say you need splat operator, all this complexity is inevitable (of course, I can work around it by not using it, but then how do you all use it?) -Kedar > > 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 -- Posted via http://www.ruby-forum.com/.