初始化哈希值

Pau*_*aul 15 ruby hash

我经常写这样的东西:

a_hash['x'] ? a_hash['x'] += ' some more text' : a_hash['x'] = 'first text'
Run Code Online (Sandbox Code Playgroud)

应该有更好的方法来做到这一点,但我找不到它.

ram*_*ion 30

使用a创建初始值有两种方法Hash.

一种是将一个对象传递给Hash.new.这在许多情况下都很有效,特别是如果对象是冻结值,但如果对象具有内部状态,则可能会产生意外的副作用.由于在没有指定值的情况下在所有键之间共享同一对象,因此修改一个对象的内部状态将全部显示.

a_hash = Hash.new "initial value"
a_hash['a'] #=> "initial value"
# op= methods don't modify internal state (usually), since they assign a new
# value for the key.
a_hash['b'] += ' owned by b' #=> "initial value owned by b"
# other methods, like #<< and #gsub modify the state of the string
a_hash['c'].gsub!(/initial/, "c's")
a_hash['d'] << " modified by d"
a_hash['e'] #=> "c's value modified by d"
Run Code Online (Sandbox Code Playgroud)

另一种初始化方法是传递Hash.new一个块,每次为没有值的键请求值时都会调用该块.这允许您为每个键使用不同的值.

another_hash = Hash.new { "new initial value" }
another_hash['a'] #=> "new initial value" 
# op= methods still work as expected
another_hash['b'] += ' owned by b'
# however, if you don't assign the modified value, it's lost,
# since the hash rechecks the block every time an unassigned key's value is asked for
another_hash['c'] << " owned by c" #=> "new initial value owned by c"
another_hash['c'] #=> "new initial value"
Run Code Online (Sandbox Code Playgroud)

该块传递两个参数:要求哈希值和使用的密钥.这使您可以选择为该键分配值,以便每次给定特定键时都会显示相同的对象.

yet_another_hash = Hash.new { |hash, key| hash[key] = "#{key}'s initial value" }
yet_another_hash['a'] #=> "a's initial value"
yet_another_hash['b'] #=> "b's initial value"
yet_another_hash['c'].gsub!('initial', 'awesome')
yet_another_hash['c'] #=> "c's awesome value"
yet_another_hash #=> { "a" => "a's initial value", "b" => "b's initial value", "c" => "c's awesome value" }
Run Code Online (Sandbox Code Playgroud)

最后一种方法是我经常使用的方法.它对于缓存昂贵计算的结果也很有用.


Dan*_*uis 5

您可以在创建哈希时指定初始值:

a_hash = { 'x' => 'first text' }
// ...
a_hash['x'] << ' some more text'
Run Code Online (Sandbox Code Playgroud)