Closed9

%記法

nogunogu

%i(小文字)
要素がシンボルの配列を書くことができる。

%i[apple banana kiwi peach]
=> [:apple, :banana, :kiwi, :peach]
nogunogu

%I(大文字)
要素がシンボルの配列を書くことができるかつ、式展開を行うことができる

red_fruits = "apple"

%I[#{red_fruits} banana kiwi peach orange]
=> [:apple, :banana, :kiwi , :peach, :orange]
nogunogu

%w(小文字)
要素が文字列の配列を書くことができる

%w[apple banana kiwi peach orange]
=> ["apple", "banana", "kiwi", "peach", "orange"]
nogunogu

%W(大文字)
要素が文字列の配列を書くことができるかつ、式展開を行うことができる

red_fruits = "apple"

%W[#{red_fruits} banana kiwi peach orange]
=> ["apple", "banana", "kiwi", "peach", "orange"]
nogunogu

%q(小文字)
対象をシングルクォートで囲んでくれる

fruits = %q(apple banana kiwi peach orange)
puts fruits
=> apple banana kiwi peach orange

シングルクォートで囲っているため式展開は行われない

nogunogu

%Q(大文字)
対象をダブルクォートで囲んでくれる

fruits = %Q(apple banana peach orange)
puts fruits
=> apple banana kiwi peach orange

ダブルクォートで囲んでいるため式展開が行われる

red_fruits = "apple"
fruits = %Q("#{red_fruits}" banana kiwi peach orange)
puts fruits
=> "apple" banana kiwi peach orange
nogunogu

%s
対象をシンボルとして生成してくれる

%s(RubyonRails)
=> :RubyonRails

%s(テスト)
=> :テスト
nogunogu

%x
出力コマンドを実行してくれる

# railsのバージョン確認
%x(rails -v)
=> "Rails 6.1.4.1"

# 明日の日時を表示
%x(date -d tomorrow)
=> "Fri Dec 10 00:37:43 JST 2021"
nogunogu

%r
正規表現のリテラルである/を省略できる記法

%r(test)
=> /test/

%r(test test)
=> /test test/

URLの正規表現を記述する際に使えそう

# %rを使用しない場合
/https:\/\/techtechmedia.com\//

# %rを使用した場合
%r(https://techtechmedia.com/)
このスクラップは6ヶ月前にクローズされました