Differences between literals and constructors? ([] vs Array.new and {} vs Hash.new)

前端 未结 3 1120
遥遥无期
遥遥无期 2021-02-05 05:39

I was curious to know more differences between [] and Array.new and {} and Hash.new

I ran same benchmarks on it and seems like the shorthands are winners



        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 06:15

    Robert already mentioned the default value of the Hash.new

    You may also use compley 'default'-values with the block variant of Hash.new:

    x = Hash.new { |hash, key|
      hash[key] = key * 2
    }
    
    p x      #-> {}
    p x[1]   #-> 2
    p x      #-> {1=>2}
    

    Array.new can also be used to get default values:

    p Array.new(5, :a)  #-> [:a, :a, :a, :a, :a]
    

提交回复
热议问题