如何进一步压缩此代码?

时间:2012-01-10 10:27:30

标签: ruby

这行代码可以变得更紧凑吗?

db_tables_scanned = {}
IO.readlines(resume_log_file).each { |db_table| db_tables_scanned[db_table.split(".")[0].strip] << db_table.split(".")[1].strip if db_table.include? '.' } if resume and File.exists?(resume_log_file)

1 个答案:

答案 0 :(得分:3)

你想要一个单行程?这是一个单行:

db_tables_scanned = resume and File.exists?(resume_log_file) ? Hash[IO.readlines(resume_log_file).map { |db_table| db_table.split(".").map(&:strip) if db_table.include? '.' }.compact] : {}

当然这段代码很可怕。没有必要为获得更少的代码行而着迷。代码必须:

  1. 是人类可读的
  2. 使用最恰当和惯用的语言抽象。
  3. 在这种情况下,让我们在行中分解它,并使用Hash[pairs_of_keys]来构建哈希:

    db_tables_scanned = if resume and File.exists?(resume_log_file)
      Hash[IO.readlines(resume_log_file).map do |db_table|
        if db_table.include?('.')
          db_table.split(".").first(2).map(&:strip)
        end  
      end.compact]
    else
      {}
    end
    
相关问题