LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby] Arrayを楽に書く %記法

Last updated at Posted at 2018-08-17

Arrayを%記法で書く

ArrayやHashを''(シングルクオート)で囲ったり、,(カンマ)で区切ったりしなくていいのでスッキリかける

%w[hoge fuga piyp]
=> ["hoge", "fuga", "piyo"]

大文字で書くと""(ダブルクオート)で囲ったのと同じ意味になり式展開ができる

変数を定義
hoge = 'hoge'

小文字だと展開できない
%w[#{hoge} fuga piyp]
=> ["#{hoge}", "fuga", "piyo"]

大文字だと展開できる
%W[#{hoge} fuga piyp]
=> ["hoge", "fuga", "piyo"]

[]で囲んでいる部分は、!!とかでもいいけど基本[]で書くらしい

%W!#hoge} fuga piyp!

シンボルの配列を作る場合は %i を使う

%i[hoge fuga piyo]
=> [:hoge, :fuga, :piyo]

おわり

最近JSばかり書いていてRubyを忘れてきていたので復習がてら勉強しています。

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