Ruby array creation, Array.new vs []

前端 未结 5 2122
时光取名叫无心
时光取名叫无心 2020-12-03 02:49

What\'s the difference between these two statements? I use them in my rails app and to me it looks like they do the same thing

array_a = Array.new
array_b =          


        
5条回答
  •  无人及你
    2020-12-03 03:14

    There is no difference, but...

    As others have already answered you

    Those two statements are functionally identical

    But there are guidelines to orient when you should use each one (so your code is easier to read). The reason behind that is:

    Programs must be written for people to read, and only incidentally for machines to execute.

    from: https://github.com/rubocop-hq/ruby-style-guide#literal-array-hash

    Prefer literal array and hash creation notation (unless you need to pass parameters to their constructors, that is).

    So if you are creating an empty array [] is the best option, but if you need to create your array with a set of N nil objects, than Array.new(N) is what you should write.

提交回复
热议问题