From: dblack@... Date: 2006-11-27T07:52:37+09:00 Subject: Re: ruby and list comprehension Hi -- On Mon, 27 Nov 2006, James Cunningham wrote: > On 2006-11-25 18:47:26 -0500, Brad Tilley said: > >> In Python, I can do this to arrays: >> >> added = [x for x in new_data if x not in old_data] >> removed = [x for x in old_data if x not in new_data] >> same = [x for x in new_data if x in old_data] >> >> I believe this is known as list comprehension in Python. How is this done >> in >> Ruby? >> >> Thanks, >> Brad > > I found this while web searching for the same thing recently; I can't recall > where I found it. It's a cute little hack. > > class Array > def comprehend > return self unless block_given? > result = [] > self.each { |i| result.push yield(i) } > result.compact > end > end > > Then: > > added = new_data.comprehend { |x| x if not old_data.include? x } > removed = old_data.comprehend { |x| x if not new_data.include? x } > same = new_data.comprehend { |x| x if old_data.include? x } 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. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org