From: Robert Klemme Date: 2011-03-26T19:35:36+09:00 Subject: Re: critique please On 26.03.2011 04:12, Charles Oppenheimer wrote: > Folks, the first ruby I've written that I actually needed (I shortened > the actual strings I was comparing, which were very long). So > thought I'd ask, before I write the next one - is there a more elegant > way to do this, or conventions that are usually used? > > > Thanks! > > globalcampaigns = "item1, item2, item3, item4, item5" > premiercampaigns = "item1, item2" > basiccampaigns = "item3, item4" > > > globalarray = globalcampaigns.split(",") > premarray = premiercampaigns.split(",") > basicarray = basiccampaigns.split(",") > > #globalarray.each {|elt| puts elt} > > combo = premarray | basicarray > diff = globalarray - combo > > diff.each {|elt| puts elt} If those are large I'd use Set: require 'set' globalcampaigns = "item1, item2, item3, item4, item5" premiercampaigns = "item1, item2" basiccampaigns = "item3, item4" res = globalcampaigns.split(/,/).to_set. subtract(premiercampaigns.split(/,/).to_set). subtract(basiccampaigns.split(/,/).to_set) puts res.to_a Note that there are some issues with regard to whitespace. You could also do gc = globalcampaigns.split(/\s*,\s*/).to_set [premiercampaigns, basiccampaigns].each do |str| str.scan /[^,]+/ do |item| gc.delete item.strip end end puts gc.to_a Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/