ruby의 각 루프에서 각 행의 끝에 쉼표를 삽입하려고합니다. 나는 마지막 줄에 쉼표를 넣고 싶지 않다. 내가 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