簡體   English   中英

每個循環的Ruby最后迭代

[英]Ruby Last Iteration of Each Loop

我正在嘗試在ruby的每個循環中的每行末尾插入一個逗號。 我不要在最后一行使用逗號。 我知道array.join(',')功能,但是在這種情況下我有點困惑。

如何重構我第一次嘗試做我需要做的事情?

重要行

@headers.each do |header|
          file.puts "`#{table[:source_database]}`.`#{table[:current_name]}`.`#{header[:current_name]}` AS `#{header[:magi_name]}`#{("," unless @headers.last == header)}" if header[:table_id] == table[:id]
        end

全班

class Table < ActiveRecord::Base        
  has_many :headers

  #--------------------------------------------------------------------------------------------------#

  def self.generate
    @tables = Table.select([:id, :source_database, :current_name, :magi_name])
    @headers = Header.select([:id, :table_id, :current_name, :magi_name])

    File.new("magi_generation.sql", "w")
    @tables.each do |table|
      File.open("magi_generation.sql", "a+") do |file|
        file.puts "#Drops current view #{table[:magi_name]} and then recreates it using updated columns"
        file.puts "DROP VIEW IF EXISTS `#{table[:magi_name]}`;"
        file.puts "CREATE ALGORITHM=UNDEFINED DEFINER=`user`@`127.0.0.1` SQL SECURITY DEFINER VIEW `#{table[:magi_name]}`"
        file.puts "AS select"
        @headers.each do |header|
          file.puts "`#{table[:source_database]}`.`#{table[:current_name]}`.`#{header[:current_name]}` AS `#{header[:magi_name]}`#{("," unless @headers.last == header)}" if header[:table_id] == table[:id]
        end
        file.puts "FROM `#{table[:source_database]}`.`#{table[:current_name]}`;"
        file.puts ""
      end
    end

  end

end

您可以使用為您提供當前元素和索引的each_with_index 這樣,您可以將數組的大小與當前元素進行比較。

但是,我不喜歡這種方法。 在您的情況下,這並不干凈,因為您正在循環中過濾記錄。 我寧願過濾記錄,然后僅循環有效記錄。

file.puts @headers.
    # keep only elements where the condition matches
    select { |header| header[:table_id] == table[:id] }.
    # convert each element into a line
    map { |header| "`#{table[:source_database]}`.`#{table[:current_name]}`.`#{header[:current_name]}` AS `#{header[:magi_name]}`" }.
    # merge everything into a single string
    join(", ")

隨意處理所有內容,將逗號和換行符放在最后,然后將其放入String變量中。 設置完畢后, chop的字符串的最后兩個字符,然后將其寫入文件。

for_file = ""
@header.each do |header|
   for_file << header + ",\n"
end
for_file.chop.chop # Gets rid of last newline and comma
file.puts for_file

我意識到我的示例循環不包含您在循環中所做的工作,但重要的是將其放入字符串中,然后.chop.chop

另外,不要在每行中都使用file.puts ... ,而要考慮heredoc。

file.puts <<EOF
SELECT 'nothing'
FROM dual
UNION
SELECT 'something'
FROM dual;
EOF

它可能會使您的SQL更具可讀性,並且您仍然可以使用字符串插值。

這就是我在自己的腳本中通過字符串插值生成SQL代碼的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM