How might you specify a default value for a hash?
How might you specify a default value for a hash?
In Ruby, specifying a default value for a hash can be achieved in several ways, depending on the behavior you want when a key that does not exist is accessed. Here are the primary methods to set default values:
Hash.new with an ArgumentThe simplest way to specify a default value for a hash is by passing the default value as an argument to Hash.new. This default value will be returned whenever a key that does not exist in the hash is accessed.
h = Hash.new("default")
h[:nosuch] # => "default"
This method is straightforward and works well for immutable default values.
Hash.newIf you need a more dynamic approach to default values, you can provide a block to Hash.new. The block will be executed whenever a key is accessed that does not exist in the hash. This is particularly useful if you want the default value to be computed or if you want to perform certain actions when nonexistent keys are accessed.
h = Hash.new { |hash, key| hash[key] = "Default for #{key}" }
h[:nosuch] # => "Default for nosuch"
h[:nosuch] # => "Default for nosuch"
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.