Сначала о различиях синтаксиса в руби версии 1.8 и 1.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hash1 = { :key => 'value' } #стандартный синтаксис | |
hash2 = { key: 'value' } #новый синтаксис в 1.9 | |
hash3 = { key: :value } #особенно удобно в новом синтаксисе хранить ключи |
Создание пустого хеша
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
empty_hash = {} | |
empty_hash = Hash.new |
Проблема с Hash.new в том, что нельзя хеш сразу заполнить значениями, как при первом способе. Для чего же тогда используется этот синтаксис? Ответ состоит в том, что с помощью Hash.new можно установить значение по умолчанию для несуществующих ключей.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
counter = Hash.new(0) # => {} | |
counter[:monkey] += 1 # => 1 | |
counter[:monkey] += 2 # => 2 | |
counter # => {:monkey => 3} |
Сравните это со следующим
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
counter = {} # => {} | |
counter[:monkey] += 1 # Ошибка! NoMethodError: undefined method `+' for nil:NilClass |
Таким образом, хеши, созданные с помощью фигурных скобок, имеют значение по умолчанию nil.
В каких случаях удобно использовать Hash.new? Например, для возврата кодов HTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
STATUS_MESSAGES = Hash.new(:undefined).merge({ | |
200 => :ok, | |
201 => :created, | |
202 => :accepted | |
} | |
STATUS_MESSAGES[200] # => :ok | |
STATUS_MESSAGES[999] # => :undefined |
Теперь вместо nil возвращается :undefined, что выглядит более ясно.
Комментариев нет:
Отправить комментарий