Help us understand the problem. What is going on with this article?

Ruby の文字列配列・シンボル配列を複数行で書く

以前書いた Ruby の正規表現を複数行で書く の続編です。初心者向け。

文字列の配列

文字列の配列を書くとき,%w が使えますよね。

%w[apple banana cherry durian] #=> ["apple", "banana", "cherry", "durian"]

しかし,リストが長くなると見にくくなります。また,ソースコードを修正したとき,差分を取っても違いが分りづらくなります。

%w は改行も区切りとして使え,かつ先頭・末尾の区切り記号は無視されますので,項目ごとに改行してはどうでしょうか。

%w[
  apple
  banana
  cherry
  durian
]

これだと,要素の一部を修正したとき,差分を取れば以下のようにどこが変更になったか一目で分ります。

 %w[
   apple
   banana
-  chely
+  cherry
   durian
 ]

シンボルの配列

シンボルの配列は,%w の代わりに %i を使うだけで,文字列の配列と同じです。

field_names = %i[
  title
  publisher
  published_year
  price
]

#=> [:title, :publisher, :published_year, :price]

参考

リファレンスマニュアル:%記法

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away