William James
2/12/2008 8:33:00 AM
On Feb 12, 1:45 am, Robert Klemme <shortcut...@googlemail.com> wrote:
> 2008/2/12, Adam Akhtar <adamtempor...@gmail.com>:
>
> > the reg exp. looks good but when i try to apply it to help me romove
> > duplicates from a list it doesnt seem to work
>
> > list = %w{adam Adam bobby Bobby wild wILd}
> > list.sort
>
> The line above is ineffective because you do not sort the original list.
>
> > list.each_index do |x|
> > list.delete_at(x) if (/list[x]/i =~ list[x+1]) #remove entries which
> > have same spelling but in diff. case
> > end
> > puts ""
> > puts list
>
> I would use another algorithm because of efficiency:
>
> #!/bin/env ruby
>
> require 'set'
>
> # ensure random order
> list = %w{adam Adam bobby Bobby wild wILd}.sort_by { rand }
> dups = Set.new
>
> p list
> list.delete_if {|w| not dups.add? w.downcase }
> p list
We don't need sets for this.
list = %w{adam Adam bobby Bobby wild wILd}.sort_by { rand }
==>["wild", "bobby", "Bobby", "wILd", "Adam", "adam"]
list.map{|x| x.upcase}.uniq
==>["WILD", "BOBBY", "ADAM"]
First "inject"; now, a set fetish?