Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

357
Vistas
Working with Hashes that have a default value

Am learning to code with ruby. I am learning about hashes and i dont understand this code: count = Hash.new(0). It says that the 0 is a default value, but when i run it on irb it gives me an empty hash {}. If 0 is a default value why can't i see something like count ={0=>0}. Or is the zero an accumulator but doesn't go to the keys or values? Thanks

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

0 will be the fallback if you try to access a key in the hash that doesn't exist

For example:

count = Hash.new -> count['key'] => nil

vs

count = Hash.new(0) -> count['key'] => 0

over 4 years ago · Santiago Trujillo Denunciar

0

To expand on the answer from @jeremy-ramos and comment from @mu-is-too-short.

There are two common gotcha's with defaulting hash values in this way.

1. Accidentally shared references.

Ruby uses the exact same object in memory that you pass in as the default value for every missed key.

For an immutable object (like 0), there is no problem. However you might want to write code like:

hash = Hash.new([])
hash[key] << value

or

hash = Hash.new({})
hash[key][second_key] = value

This will not do what you'd expect. Instead of hash[unknown_key] returning a new, empty array or hash it will return the exact same array/hash object for every key.

so doing:

hash = Hash.new([])
hash[key1] << value1
hash[key2] << value2

results in a hash where key1 and key2 both point to the same array object containing [value1, value2]

See related question here

Solution

To solve this you can create a hash with a default block argument instead (which is called whenever a missing key is accessed and lets you assign a value to the missed key)

hash = Hash.new{|h, key| h[key] = [] }

2. Assignment of missed keys with default values

When you access a missing key that returns the default value, you might expect that the hash will now contain that key with the value returned. It does not. Ruby does not modify the hash, it simply returns the default value. So, for example:

hash = Hash.new(0) #$> {} 
hash.keys.empty? #$> true
hash[:foo] #$> 0
hash[:foo] == 0 #$> true
hash #$> {}
hash.keys.empty? #$> true

Solution

This confusion is also addressed using the block approach, where they keys value can be explicitly set.

over 4 years ago · Santiago Trujillo Denunciar

0

The Hash.new docs are not very clear on this. I hope that the example below clarifies the difference and one of the frequent uses of Hash.new(0).

The first chunk of code uses Hash.new(0). The hash has a default value of 0, and when new keys are encountered, their value is 0. This method can be used to count the characters in the array.

The second chunk of code fails, because the default value for the key (when not assigned) is nil. This value cannot be used in addition (when counting), and generates an error.

count = Hash.new(0)

puts "count=#{count}"
# count={}

%w[a b b c c c].each do |char|
  count[char] += 1
end

puts "count=#{count}"
# count={"a"=>1, "b"=>2, "c"=>3}


count = Hash.new

puts "count=#{count}"

%w[a b b c c c].each do |char|
  count[char] += 1
  # Fails: in `block in <main>': undefined method `+' for nil:NilClass (NoMethodError)
end

puts "count=#{count}"

SEE ALSO:

What's the difference between "Hash.new(0)" and "{}"

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda