简体   繁体   中英

Ruby- find strings that contain letters in an array

I've googled everywhere and can't seem to find an example of what I'm looking for. I'm trying to learn ruby and i'm writing a simple script. The user is prompted to enter letters which are loaded into an array. The script then goes through a file containing a bunch of words and pulls out the words that contain what is in the array. My problem is that it only pulls words out if they are in order of the array. For example...

characterArray = Array.new;
puts "Enter characters that the password contains";
characters = gets.chomp;
puts "Searching words containing #{characters}...";

characterArray = characters.scan(/./);
searchCharacters=characterArray[0..characterArray.size].join;

File.open("dictionary.txt").each { |line| 
    if line.include?(searchCharacters)
        puts line;
    end
 }

If i was to use this code and enter "dog" The script would return dog doggie

but i need the output to return words even if they're not in the same order. Like... dog doggie rodge

Sorry for the sloppy code. Like i said still learning. Thanks for your help.

PS. I've also tried this...

File.open("dictionary.txt").each { |line| 
    if line =~ /[characterArray[0..characterArray.size]]/
        puts line;
    end
}

but this returns all words that contain ANY of the letters the user entered

First of all, you don't need to create characterArray yourself. When you assign result of function to a new variable, it will work without it.

In your code characters will be, for example, "asd". characterArray then will be ["a", "s", "d"]. And searchCharacters will be "asd" again. It seems you don't need this conversion.

characterArray[0..characterArray.size] is just equal to characterArray .

You can use each_char iterator to iterate through characters of string. I suggest this:

puts "Enter characters that the password contains";
characters = gets.chomp;

File.open("dictionary.txt").each { |line| 
  unless characters.each_char.map  { |c| line.include?(c) }.include? false
    puts line;
  end
}

I've checked it works properly. In my code I make an array:

characters.each_char.map  { |c| line.include?(c) }

Values of this array will indicate: true - character found in line , false - character not found. Length of this array equals to count of characters in characters . We will consider line good if there is no false values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM