6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

覚えた使えるRubyトリック _ %w記法

Last updated at Posted at 2016-03-15

2016年 初春。
アルコール漬けのチンピラからプログラマに転身した私が覚えたトリックを備忘録兼ねてまとめるTips_Ruby編


ソース読んでて 「%wって何だよ?」ってなっていたし、コードレビューで教えてもらったので忘れないうちに書いとく。
Rubyは見慣れない色んな書き方があるけど、覚えると超ラクかつ見やすいってことが多い。
##%w 文字列の配列を作ってくれる

#普通の配列宣言
array = ["red","green","blue"]

#%wを使う場合
array = %w(red green blue)
=> ["red","green","blue"]

こっちの方が書くのも早い。
せっかくなので、調べると大文字もあるみたい

##%W 文字列の配列を作ってくれる。(配列の中で式展開してくれる)
こっちは式展開が使えるので、


color = "青"

#小文字の%w記法だと、、
%w(red green color)
=> ["red","green","color"]

%w(red green #{color})
=> ["red","green","#{color}"]

#そこで、大文字verを使うと
%W(red green #{color})
=> ["red","green","青"]

大文字のはともかく、小文字のはよく使いそう。
もっかい言うけど書くのが楽。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?