Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

string - Properly combining words in a file using Ruby

I have a file full of words and I am trying to write a script that basically makes every combination of 2 words from that list to another list.

require 'tempfile'
require 'fileutils'

path = 'Lst.lst'
temp_file = Tempfile.new('lst2.lst')
begin
  File.open(path, 'r') do |file|
    file.readlines(file).each do |line|
         file.each_line do |baseline|
                temp_file.puts line.gsub("
", '') + baseline
        end
    end
 end
  temp_file.close
  FileUtils.mv(temp_file.path, 'lst2.lst')
ensure
  temp_file.close
  temp_file.unlink
end

The script runs but the outer loop only runs once. How can I fix this?

question from:https://stackoverflow.com/questions/65944972/properly-combining-words-in-a-file-using-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Iterators Instead of Nested Loops

In general, explicit looping in Ruby is not idiomatic, although there are always exceptions. You'll often find it easier to perform what you want using an object's native iterators.

Given a file like word_list.txt with a small set of contents like this:

a
b
c
d
e
f
g

you can use Array#combination to make your pairwise combinations. For example, with Ruby 3.0.0:

words      = File.readlines('word_list.txt').map &:chomp
word_pairs = words.combination 2

File.open('new_list.txt', 'w') do |file|
  word_pairs.map { file.puts "#{_1}#{_2}" }
end 

You can then verify the results of your output in the shell:

$ cat new_list.txt 
a   b
a   c
a   d
a   e
a   f
a   g
b   c
b   d
b   e
b   f
b   g
c   d
c   e
c   f
c   g
d   e
d   f
d   g
e   f
e   g
f   g

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...