From: James Cunningham Date: 2006-11-27T22:00:06+09:00 Subject: Re: ruby and list comprehension On 2006-11-27 03:30:58 -0500, Robert Klemme said: > On 27.11.2006 01:01, James Cunningham wrote: >> On 2006-11-26 17:52:37 -0500, dblack@wobblini.net said: >>> I'm not getting how that's better than: >>> >>> added = new_data.select {|x| not old_data.include?(x) } >>> >>> (or the reject equivalent) and so on. > >> I should have clarified. In your example there's no difference, but the >> above gives a general replacement for list comprehensions. >> >> irb(main):018:0> (1..25).to_a.comprehend { |x| x**2 if not x % 2 == 0 } >> => [1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625] > > Frankly, I am not sure I find this better than using the built in methods: > > irb(main):001:0> (1..25).inject([]) {|a,x| a << x**2 unless x % 2 == 0; a} > => [1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625] > > irb(main):002:0> (1..25).inject([]) {|a,x| a << x**2 if x % 2 == 1; a} > => [1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625] > > irb(main):003:0> (1..25).select {|x| x % 2 == 1}.map! {|x| x**2} > => [1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625] > > Kind regards > > robert That's fair enough, but I think list comprehension is clearer than method chaining and one-liner array accumulation. I'm afraid a << x**2 if x % 2 == 1; a is perhaps just a little less elegant than x**2 if x % 2 == 1 I think the nicest thing about Ruby, though, is that it's even possible. Best, James