33
28

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]配列の定義方法まとめ

Last updated at Posted at 2017-02-04

[]を使う

>> array = ["hello", "world"]
=> ["hello", "world"]
>> [*1..10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.newを使う

>> Array.new
=> []
>> Array.new(3)
=> [nil, nil, nil]
>> Array.new(3, 3)
=> [3, 3, 3]

%wや%iを使う

使える場合

  • 文字列の配列(空白文字を含まない)
  • シンボルの配列(空白文字を含まない)
>> %w(Ruby Perl Python)
=> ["Ruby", "Perl", "Python"]
>> %i(Ruby Perl Python)
=> [:Ruby, :Perl, :Python]

結局どの定義がいいの?

Githubとクックパッドのスタイルガイドを読んだ感じだと、Array.newは引数がない場合は使わないほうが良い。
あとは、%記法(%wと%i)が使える場合は、使うようにする。
もっと詳しく見たい場合は参考文献のリンクからスタイルガイドを見て見てください。すごくためにまりました。

# 悪い例
arr = Array.new
hash = Hash.new

# 良い例
arr = []
hash = {}
# 悪い例
STATES = ['draft', 'open', 'closed']
STATES = [:draft, :open, :closed]

# 良い例
STATES = %w(draft open closed)
STATES = %i(draft open closed)

参考文献

33
28
2

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
33
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?