Вот гораздо более простая версия сценария неиспользования, который я использую:
class String
# Strip leading whitespace from each line that is the same as the
# amount of whitespace on the first line of the string.
# Leaves _additional_ indentation on later lines intact.
def unindent
gsub /^#{self[/\A[ \t]*/]}/, ''
end
end
Используйте его так:
foo = {
bar: <<-ENDBAR.unindent
My multiline
and indented
content here
Yay!
ENDBAR
}
#=> {:bar=>"My multiline\n and indented\n content here\nYay!"}
Если первая строка может иметь отступ большечем другие, и вы хотите (например, Rails) удалить отступы на основе строки с наименьшим отступом, вместо этого вы можете использовать:
class String
# Strip leading whitespace from each line that is the same as the
# amount of whitespace on the least-indented line of the string.
def strip_indent
if mindent=scan(/^[ \t]+/).min_by(&:length)
gsub /^#{mindent}/, ''
end
end
end
Обратите внимание, что если вы сканируете на \s+
вместо [ \t]+
, выможет закончить тем, что удаляет переводы строк из вашего heredoc вместо пробелов.Не желательно!