Câu hỏi phỏng vấn Ruby
Câu hỏi

How might you specify a default value for a hash?

Câu trả lời

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:

Using Hash.new with an Argument

The 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[1].

Using a Block with Hash.new

If 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"

In this example, the block not only returns a default value but also inserts that value into the hash, making the key exist with the computed default value[1].

Using Hash#default and Hash#default=

You can also get or set the default value of a hash using the #default and #default= methods. This is useful if you need to change the default value after the hash has been created.

h = {}
h.default = "default"
h[:nosuch] # => "default"

This method changes the default value for all keys that do not exist in the hash[1].

Using Hash#default_proc and Hash#default_proc=

For a more flexible and dynamic default value, you can use a default proc. This allows you to specify a block that will be called to determine the default value whenever a key is accessed that does not exist in the hash.

h = Hash.new
h.default_proc = proc { |hash, key| hash[key] = "Default for #{key}" }
h[:nosuch] # => "Def...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What are some disadvantages of a case statement versus repeated elsif
statements?

entry

Which core object includes the "Kernel" module?

junior

Explain each of the following operators and how and when they should be used

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào