LoginSignup
23
14

More than 5 years have passed since last update.

rubyで複数行の文字列

Posted at

複数行の長い文字列を作成する場合にはヒアドキュメントを使用することができる。

書式は以下の通り。

<<"識別子"
文字列
文字列
文字列
最終行
識別子

ルール

  • 識別子をダブルクオーテーションで囲んだ場合は文字列をダブルクオーテーションで囲んだ場合と同じ
  • シングルクオーテーションで囲んだ場合は文字列をシングルクオーテーションで囲んだ場合と同じ
  • 単に識別子が記述された場合は、ダブルクオーテーションで囲んだ場合と同じ
  • 「<<"識別子"」の代わりに「<<-"識別子"」を使うと最後の識別子の前に空白やタブを記述することが可能

識別子には任意の文字列を指定できるが、「EOS」などがよく使われているらしい。(EOS=End of String)
こんな感じ。

<<"EOS"
hello, world!
hello, ruby!
hello, ruby on rails!
EOS

変数に入れることもできる。

str = <<-EOS
hello, world!
hello, ruby!
hello, rails!
EOS

p str #=>"hello, world!\nhello, ruby!\nhello, rails!\n"
23
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
14