[英]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.