From: Robert Klemme Date: 2006-11-27T17:35:08+09:00 Subject: Re: ruby and list comprehension 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