0
0

More than 1 year has passed since last update.

【Ruby】%記法について

Posted at

文字列

%, %Q

%および%Qは式展開できる文字列を表現します。
ダブルクォーテーションで文字列を囲んだ"文字列"と同等になります。

%(a b c)
# => "a b c"

a, b, c = 1, 2, 3
%(#{a} #{b} #{c})
# => "1 2 3"
%Q(#{a} #{b} #{c})
# => "1 2 3" 

%q

%q%%Qと同様に文字列を表現しますが、式展開ができない点で異なります。
シンブルクォーテーションで文字列を囲んだ'文字列'と同等になります。

%q(a b c)
# => 'a b c'

a, b, c = 1, 2, 3
%q(#{a} #{b} #{c})
# => "\#{a} \#{b} \#{c}"

配列

%W

%Wはスペースで区切った文字列を含む配列を表します。

a, b, c = 1, 2, 3
%W(#{a} #{b} #{c})
# => ["1", "2", "3"]

%w

%w%Wと同様に配列を表しますが、式展開ができない点で異なります。

a, b, c = 1, 2, 3
%w(a b c)
# => ['a', 'b', 'c']

%I

%Iはシンボルの配列を表現します。

a, b, c = 1, 2, 3
%I(#{a} #{b} #{c})
#=> [:"1", :"2", :"3"]

%i

%i%Iと同様にシンボルの配列を表しますが、式展開ができない点で異なります。

a, b, c = 1, 2, 3
%i(a b c)
# => [:a, :b, :c]

シンボル

%s

%sはシンボルを表します。

%s(a b c)
# => :"a b c"

コマンド

%x

%xはコマンドを実行できます。
バッククォーテーションで囲んだ`some command`と同等です。

%x(date)
# => "Thu Oct 20 18:25:04 JST 2022\n"

正規表現

%r

%rは正規表現を表します。

%r(^http://)
# => /^http:\/\//
0
0
0

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
0
0