Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Javaプログラマーが学ぶRuby基礎/Rubyの文字列/文字列中の式

概要

Rubyの文字列について引き続き説明します。
※関連記事はこちら
Javaプログラマーが学ぶRuby基礎/Rubyの文字列1(http://d.hatena.ne.jp/tbpg/20120201/1328113110
Javaプログラマーが学ぶRuby基礎/Rubyの文字列/ヒアドキュメント(http://d.hatena.ne.jp/tbpg/20120203/1328282154

文字列中の式

ダブルクォーテーションの文字列中に以下の書式を使うことで式を使用できます。

#{}
サンプルコード
puts("名前は #{'伊藤'} です")
puts(%Q|名前は #{'田中'} です|)
puts(%Q|4*5は #{4*5} です|)
time = Time.new
puts(%Q|現在時刻は #{time} です|)
出力結果
名前は 伊藤 です
名前は 田中 です
4*5は 20 です
現在時刻は 2012-02-02 17:50:28 +0900 です
ヒアドキュメントとも連携可能
column1Value = "tanaka"
column2Value = "24"
puts(%Q|ヒアドキュメントと連携#{<<"EOS"}|)

select
	column1,column2
from
	table1
where
	column1 = "#{column1Value}"
	column2 = "#{column2Value}"
EOS
出力結果
ヒアドキュメントと連携
select
	column1,column2
from
	table1
where
	column1 = "tanaka"
	column2 = "24"