user8927175
user8927175

Reputation:

How to remove words that have the same letter more than once?

I am trying to remove words that have more that have the same letter more than once. I have tried squeeze but all that is doing is removing words that have duplicate letters next to each other.

Here is the code at the moment:

array = []

File.open('word.txt').each do |line|                                               
  if line.squeeze == line 
    array << line
  end
end

Input from word.txt

start
james
hello
joins
regex

Output that I am looking for

james
joins

Any suggestions on how I can get around this.

Upvotes: 0

Views: 198

Answers (2)

Stefan
Stefan

Reputation: 114168

You could use a regular expression, for example:

re = /
  (.)  # match and capture a single character
  .*?  # any number of characters in-between (non-greedy)
  \1   # match the captured character again
/x

Example:

'start'[re] #=> "tart"
'james'[re] #=> nil
'hello'[re] #=> "ll"
'joins'[re] #=> nil
'regex'[re] #=> "ege"

It can be passed to grep to return all matched lines:

IO.foreach('word.txt').grep(re)
#=> ["start\n", "hello\n", "regex\n"]

or to grep_v to return the other lines:

IO.foreach('word.txt').grep_v(re)
#=> ["james\n", "joins\n"]

Upvotes: 1

spickermann
spickermann

Reputation: 106832

Perhaps something like this:

array = []

File.open('word.txt').each do |line| 
  chars = line.chars                                              
  array << line if chars.uniq == chars
end

or shorter:

array = File.open('word.txt').select { |word| word.chars.uniq == word.chars }

Upvotes: 2

Related Questions