Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

require 'benchmark'  many = 500000  Benchmark.bm do |b|   b.report("[]          \t") {many.times { [].object_id }}   b.report("Array.new   \t") { many.times { Array.new.object_id }}   b.report("{}          \t") {many.times { {}.object_id }}   b.report("Hash.new\t") { many.times { Hash.new.object_id }} end                     user     system      total        real []            0.080000   0.000000   0.080000 (  0.079287) Array.new     0.180000   0.000000   0.180000 (  0.177105) {}            0.080000   0.000000   0.080000 (  0.079467) Hash.new      0.260000   0.000000   0.260000 (  0.264796) 

I personally like to use the shorthand one's [] and {} , the code looks so cool and readable.

Any other pointer what is the difference between them? what happens behind scene that make it so better, and suggestions if any when to use which?

I found this link but was looking to get more info.

cheers.

like image 512
Pritesh Jain Avatar asked Aug 03 '12 19:08

Pritesh Jain


People also ask

What is {} in ruby?

The curly brackets { } are used to initialize hashes. The documentation for initializer case of { } is in ri Hash::[] The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.

What is Ruby hash New 0?

In short, Hash. new(some_value) sets a default value of some_value for every key that does not exist in the hash, Hash. new {|hash, key| block } creates a new default object for every key that does not exist in the hash, and Hash. new() or {} sets nil for every key.


1 Answers

With Hash.new you can set the default value of the hash for unset keys. This is quite useful if you're doing statistics, because Hash.new(0) will let you increment keys without explicitly initializing them.

like image 81
Robert K Avatar answered Oct 18 '22 07:10

Robert K