rubyのヒアドキュメントの書き方
複数行の文字列を扱う場合、ヒアドキュメントを書くとすっきりと見せれることができます。
書き方は、次のようになります。
<<EOS ... EOS
上記の...間に文字列を書いていきます。
puts <<EOS おはようございます。 我輩は猫である。 EOS → おはようございます。 我輩は猫である。
EOSはEnd of Stringという、意味で使われているので、これは別の文字でも表すことができます。
puts <<HOGE おはようございます。 我輩は猫である。 HOGE
変数展開も可能です。
class Hoge class << self def hello text = <<"EOS" my name is #{self} #{self} is often used in programming EOS puts text end end end Hoge.hello→ my name is Hoge Hoge is often used in programming
上記の書き方だと、最後のEOSの位置が気に入らない方が多いと思います。 これは、下記のように-をつけることで修正することができます。
<<-EOS EOS class Hoge class << self def hello text = <<-EOS my name is #{self} #{self} is often used in programming EOS puts text end end end Hoge.hello→ my name is Hoge Hoge is often used in programming
慣れにくい部分もあるかもしれませんが、一度使い方を覚えることができたら便利になると思います。