DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on • Edited on

[Ruby] heredocument (ヒアドキュメント)

TL;DR

use <<~EOS instead of others, then chomp it.

code and results

class HereDoc
  attr_reader :name

  def initialize
    @name = 'n350071'
  end

  def m1
    <<-'EOS'
      #{name}
    EOS
  end

  def m2
    <<-"EOS"
      #{name}
    EOS
  end

  def m3
    <<-EOS
      #{name}
    EOS
  end

  def m4
    <<~EOS
      #{name}
    EOS
  end
end

hd = HereDoc.new
hd.m1       #=> "      \#{name}\n"
hd.m2       #=> "      n350071\n"
hd.m3       #=> "      n350071\n"
hd.m4       #=> "n350071\n"
hd.m4.chomp #=> "n350071"

🔗 Parent Note

Top comments (0)