FAQ: Data Structures - Using Hash.new

This community-built FAQ covers the “Using Hash.new” exercise from the lesson “Data Structures”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Ruby

FAQs on the exercise Using Hash.new

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi!
I’m having trouble figuring out how to use . Hash.new

I don’t know why this syntax doesn’t work.

my_hash = Hash.new.capitalize! “pets” => “Mimi”

puts my_hash[“pets”]

The error message explains it…

undefined method `capitalize!’ for {}:Hash

which means that we cannot use that syntax.

my_hash = Hash.new
my_hash["pets".capitalize!] = "Mimi" 
puts my_hash    # {"Pets"=>"Mimi"}
1 Like

After trying all of the variables suggested here and those I thought of. The answer is a very simple:

pets = Hash.new

2 Likes

OMG, thank you for this. This just helped and once seen it makes sense

what is the purpose of using Hash.new?
I understand using hashes that asign values to keys. But what is Hash.new achieving if it isn’t assigning value to anything?

The .new() method on the Hash object can take a default value to assign to every new Hash.

x = Hash.new(0)
x['word'] += 1
puts x['word']    #  1

We see this employed in a word frequency hash, for instance.

2 Likes

Is there a benefit to using obj = Hash.new rather than obj = {} when they do the same thing? It seems obj = {} would be more efficient considering the difference in the number of characters.

The number of characters is not a sign of efficiency; to determine that we examine time complexity, especially of loops, and space complexity in terms of how much memory is consumed.

Declaring a literal hash is okay when the values are random data. The advantage we gain with Hash.new is an initial default value for each additional member.

Eg.

hist = Hash.new(0)

This will come up in the Build a Histogram exercise.