如何在Ruby中正确拼接SQL Heredoc字符串?
解决Ruby中Heredoc SQL片段拼接问题
你可以通过以下几种方式处理Heredoc字符串的拼接,得到期望的格式:
方法一:使用chomp去除末尾换行后拼接
chomp方法会移除字符串末尾的换行符,之后按需添加换行再拼接:
base_sql = <<-SQL select * from table SQL condition = <<-SQL where table.column = true SQL combined_sql = base_sql.chomp + "\n" + condition # 结果:"select * from table\nwhere table.column = true\n"
方法二:定义Heredoc时直接调用chomp
在Heredoc定义末尾直接链式调用chomp,提前移除末尾换行:
base_sql = <<-SQL.chomp select * from table SQL condition = <<-SQL where table.column = true SQL combined_sql = base_sql + "\n" + condition
方法三:使用字符串插值简化拼接
通过字符串插值组合处理后的片段:
combined_sql = "#{base_sql.chomp}\n#{condition}"
这些方法都能保留Heredoc带来的SQL语法高亮支持,同时得到你需要的拼接结果。
内容的提问来源于stack exchange,提问作者Drew Daniels
相关产品推荐
相关产品推荐

