2016年12月30日 星期五

Ruby Koans - Hashes

  def test_default_value_is_the_same_object
    hash = Hash.new([])

    hash[:one] << "uno"
    hash[:two] << "dos"

    assert_equal ["uno","dos"], hash[:one]
    assert_equal ["uno","dos"], hash[:two]
    assert_equal ["uno","dos"], hash[:three]

    assert_equal true, hash[:one].object_id == hash[:two].object_id
  end
這次是做這題的時候卡住了,我本來以為<<是會把值加到hash裡面去,但是其實
hash根本沒有<<,array才有
因為第一行預設了hash的值是空陣列,所以這邊才不會跳error
兩行<<其實都是把值丟到一開始預設的空陣列裡面
所以不管是hash[:one]還是hash[:two]都會得到一樣的東西
反過來說,如果一開始只是下面這樣,就會error
NoMethodError: undefined method `<<’ for nil:NilClass
hash = {}
hash[:one] << "uno"
Written with StackEdit.

沒有留言:

張貼留言