我试图在每个循环的每行结尾处插入一个逗号作为红宝石。我不想在最后一行输入逗号。我知道array.join(',')特性,但在这种情况下我有点困惑。Ruby每个循环的最后迭代
我该如何重构我的第一次尝试去做我需要的东西?
重要的行
@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并查看索引是否是最后一个? –
因此更改为@ tables.each_with_index do | table,index |然后如果index.last ==什么?我几乎已经掌握了这些概念,但还没有完全实现。 – jwg2s
index是一个数字,因此您应该将它与一个数字进行比较,例如:index == @ tables.length-1,那么您应该得到“是最后一个元素”的布尔值 – robustus