Me gustaría una explicación de algún comportamiento en Ruby con el que me encontré en los Koans.

Why does the second assert_equal below work? How does ruby associate "dos" with :two?

  def test_default_value

    hash2 = Hash.new("dos")
    hash2[:one] = 1

    assert_equal 1, hash2[:one]
    assert_equal "dos", hash2[:two]
  end

preguntado el 01 de febrero de 12 a las 22:02

1 Respuestas

El argumento para Hash.new is the "default" value - when a key isn't present, and is read, return that value instead. You can also pass a block to Hash.new to have more complex behaviour around default values.

http://ruby-doc.org/core-1.8.7/Hash.html#method-c-new

Respondido 02 Feb 12, 02:02

Also note that it returns the same value each time, so using a default value of a string (which is mutable) is unwise. At the very least, you'd want to freeze it. - Joshua Cheek

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.