コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

Rubyでパーセント記号を使って作れる配列とその種類

Ruby Style Guideに則っているとよく自動変換されちゃうあれ。

環境

$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]

出典

リテラル (Ruby 2.6.0) - %記法

文字列を扱う%wと%W

配列の要素が全て文字列のものの場合に使うことができ、要素を空白区切りで指定する。

not_parsent = ["a", "b", "c"]
# 空白区切りで表現
parsent= %w(a b c)

# 同じものである
not_parsent == parsent
# true

%W になると変数が展開できる

string = "hoge"
not_parsent = ["example", "hoge", "test"]
# 空白区切りで表現
parsent= %W(example #{string} test)

# 同じものである
not_parsent == parsent
# true

シンボルを扱う%iと%I

配列の要素がシンボルだけのものの場合に要素を空白区切りで指定する。

not_parsent = [:a, :b, :c]
# 空白区切りで表現
parsent= %i(a b c)

# 同じものである
not_parsent == parsent
# true

%I になると%W同様に変数が展開できる

string = "hoge"
not_parsent = [:example, :hoge, :test]
# 空白区切りで表現
parsent= %I(example #{string} test)

# 同じものである
not_parsent == parsent
# true

参考サイト