我不想在Ruby中重复自己

时间:2018-12-06 11:08:49

标签: ruby-on-rails ruby

我有一个脚本构成了URL列表:

arr = [['1'], [*'05'..'15'], ['78'], [*'02'..'04', *'07'..'12', 
*'15'..'27'],[*'00000'..'99999']]

file = File.new('./file_300k.txt', 'w')
    combos = arr.first.product(*arr.drop(1)).map(&:join)

comb = combos.first(300000)

comb.each do |n|
 a = n.to_f / 11
 afloat = a.round 1
 str = afloat.to_s.delete(".").reverse
 b = str[0]
 file.puts "https://blablabla.com/company/ul/#{n}#{b}"
end


    file = File.new('./file_301_600k.txt', 'w')
combos = arr.first.product(*arr.drop(1)).map(&:join)
comb = combos[300001..600000]
comb.each do |n|

    a = n.to_f / 11
    afloat = a.round 1
    str = afloat.to_s.delete(".").reverse
    b = str[0]
    file.puts "https://blablabla.com/company/ul/#{n}#{b}"

end

...

    file = File.new('./file_1__1_3.txt', 'w')
combos = arr.first.product(*arr.drop(1)).map(&:join)
comb = combos.first[1000001..1300000]
comb.each do |n|

    a = n.to_f / 11
    afloat = a.round 1
    str = afloat.to_s.delete(".").reverse
    b = str[0]
    file.puts "blablabla.com/company/ul/#{n}#{b}"

end

...

正如您所看到的,我重复我自己,因为完整的结果有超过2400万种组合,我需要一组小的TXT文档来说明我的观点。我认为这种情况也可以用另一种方式解决,但是我想使用OOP决策,因为我需要了解OOP的工作原理。谢谢!

2 个答案:

答案 0 :(得分:0)

沿着这些思路怎么样?未经测试的结果是,您无需为每个300_000再次编写循环。

ITERATE_LIMIT = 300_000

# creates enough files based on the combos count and you iteration limit
# sets @file1, @file2, ....
(combos.count.to_f / ITERATE_LIMIT).to_i.each do |i|
  instance_variable_set("@file#{i}", File.new("./file_#{i}.txt", 'w'))
end

# you regular loop
# selects the file based on the index the loop is currently on and puts the 
# string
comb.each_with_index do |n, index|
  a = n.to_f / 11
  afloat = a.round 1
  str = afloat.to_s.delete(".").reverse
  b = str[0]
  instance_variable_get("@file#{(index.to_f / ITERATE_LIMIT).to_i}").puts "https://blablabla.com/company/ul/#{n}#{b}"
end

答案 1 :(得分:0)

重复代码中发生变化的事物是

  • 文件名
  • 范围

重复代码的通用对象是

  • arr

因此,为了使其重构,请尝试创建一个方法

def build_file(name, range, arr)
  file = File.new("./file_#{name}.txt", 'w')
  combos = arr.first.product(*arr.drop(1)).map(&:join)

  combos[range].each do |n|
    a = n.to_f / 11
    afloat = a.round 1
    str = afloat.to_s.delete(".").reverse
    b = str[0]
    file.puts "https://blablabla.com/company/ul/#{n}#{b}"
  end
  file.close
end

然后将其命名为...

build_file('300k',(0..30_000), arr)
build_file('301_600k',(30_001..60_000), arr)
...