简体   繁体   English

每个循环的Ruby最后迭代

[英]Ruby Last Iteration of Each Loop

I am attempting to insert a comma at the end of each line in an each loop in ruby. 我正在尝试在ruby的每个循环中的每行末尾插入一个逗号。 I don't want the comma on the last line. 我不要在最后一行使用逗号。 I know about the array.join(',') feature but I am a little confused in this circumstance. 我知道array.join(',')功能,但是在这种情况下我有点困惑。

How can I refactor my first attempt to do what I require? 如何重构我第一次尝试做我需要做的事情?

Important Lines 重要行

@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

Full Class 全班

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

You can use each_with_index that gives you the current element and the index. 您可以使用为您提供当前元素和索引的each_with_index In this way, you can compare the size of the array with the current element. 这样,您可以将数组的大小与当前元素进行比较。

However, I don't like this approach. 但是,我不喜欢这种方法。 In your case that's not clean because you are filtering records inside the loop. 在您的情况下,这并不干净,因为您正在循环中过滤记录。 I would rather filter the records, then only loop valid records. 我宁愿过滤记录,然后仅循环有效记录。

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(", ")

Process everything like you want, putting a comma and newline at the end and throw it into a String variable. 随意处理所有内容,将逗号和换行符放在最后,然后将其放入String变量中。 After you are done, chop off the last two characters of the string and then write it to the file. 设置完毕后, 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

I realize my example loop doesn't encompass the extent of what you are doing in your loop but the important thing it putting it in a string and then .chop.chop . 我意识到我的示例循环不包含您在循环中所做的工作,但重要的是将其放入字符串中,然后.chop.chop

Also, instead of having file.puts ... for every new line, consider a heredoc. 另外,不要在每行中都使用file.puts ... ,而要考虑heredoc。

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

It might make your SQL a little more readable and you can still use string interpolation. 它可能会使您的SQL更具可读性,并且您仍然可以使用字符串插值。

This is how I generate SQL code with string interpolation in my own scripts. 这就是我在自己的脚本中通过字符串插值生成SQL代码的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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