ruby中带多行字符串的空格
我有一个多行字符串的空白问题 我的代码中有类似的东西,我正在生成一些SQLruby中带多行字符串的空格,ruby,string,multiline,Ruby,String,Multiline,我有一个多行字符串的空白问题 我的代码中有类似的东西,我正在生成一些SQL def generate_sql <<-EOQ UPDATE page SET view_count = 10; EOQ end 我可以 def generate_sql <<-EOQ UPDATE page SET view_count = 10; EOQ end 但是我的代码缩进都搞砸了,我真的不想这样 " UPD
def generate_sql
<<-EOQ
UPDATE page
SET view_count = 10;
EOQ
end
我可以
def generate_sql
<<-EOQ
UPDATE page
SET view_count = 10;
EOQ
end
但是我的代码缩进都搞砸了,我真的不想这样
" UPDATE page\n SET view_count = 10;\n"
关于如何最好地实现我所追求的目标,有什么建议吗?有这样的库供您使用
require 'dedent'
def generate_sql
<<-EOQ.dedent
UPDATE page
SET view_count = 10;
EOQ
end
像这样的事情应该可以做到:
def generate_sql
<<-EOQ.gsub("\n", " ").strip
UPDATE page
SET ...
EOQ
end
def生成\u sql
这会占用更多的空间(可能不太美观),但效果很好:
def generate_sql
text = <<-EOQ
UPDATE page
SET view_count = 10;
EOQ
text.gsub(/^#{text.match(/^\s*/)[0]}/, '')
end
Ruby 2.3.0很好地解决了这个问题。请注意示例之间波浪线/连字符的差异
hyphen_heredoc = <<-MULTILINE_STRING
One line
Second line
Indented two spaces
MULTILINE_STRING
squiggly_heredoc = <<~MULTILINE_STRING_WITH_TILDE
One line
Second line
Indented two spaces
MULTILINE_STRING_WITH_TILDE
2.3.0 :001 > puts hyphen_heredoc
One line
Second line
Indented two spaces
2.3.0 :002 > puts squiggly_heredoc
One line
Second line
Indented two spaces
hyphen\u herdeoc=我没说它不会呈现给用户
def generate_sql
text = <<-EOQ
UPDATE page
SET view_count = 10;
EOQ
text.gsub(/^#{text.match(/^\s*/)[0]}/, '')
end
"UPDATE page\n SET view_count = 10;\n"
hyphen_heredoc = <<-MULTILINE_STRING
One line
Second line
Indented two spaces
MULTILINE_STRING
squiggly_heredoc = <<~MULTILINE_STRING_WITH_TILDE
One line
Second line
Indented two spaces
MULTILINE_STRING_WITH_TILDE
2.3.0 :001 > puts hyphen_heredoc
One line
Second line
Indented two spaces
2.3.0 :002 > puts squiggly_heredoc
One line
Second line
Indented two spaces