Ruby array creation, Array.new vs []

前端 未结 5 2115
时光取名叫无心
时光取名叫无心 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:16

    [] is a shortcut to the Array class's singleton method [] which in turn creates a new Array in just the same way as Array.new, so you could probably say 'they are the same' without worrying too much.

    Note that each call to [] in irb creates a new Array:

    >> [].object_id
    => 2148067340
    >> [].object_id
    => 2149414040
    

    From Ruby's C code:

    rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
    

提交回复
热议问题