Ruby 每个循环的最后一次迭代

标签 ruby

我试图在 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(", ")

关于Ruby 每个循环的最后一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11265865/

相关文章:

ruby - 如何使用 FactoryGirl 创建一个名为 "alias"的属性?

ruby - 如何在 Minitest 中为 TCPSocket 编写多个测试

ruby-on-rails - 有关使用 migrate on Rails 的指南

ruby-on-rails - 在生产环境中运行 Watir 等慢速网络驱动程序

c++ - 在 C++ 程序中嵌入 ruby​​ 源时出错

ruby-on-rails - 使用 ActiveRecord 在 Rails 中测试具有多个数据库连接的模型

java - 合并两个文本文件的最简单脚本方法——Ruby、Python、JavaScript、Java?

ruby - Ruby 的计算机视觉库

ruby - 如何在 Ubuntu 10.04 服务器上安装 Jekyll?

ruby - sinatra 是否有任何 RSpec HTML 标签匹配器扩展?