Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
23
Help us understand the problem. What is going on with this article?
@hkengo

[Ruby]配列の定義方法まとめ

More than 3 years have passed since last update.

[]を使う

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

参考文献

23
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  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
hkengo

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
23
Help us understand the problem. What is going on with this article?