初始化哈希值

时间:2010-06-07 15:30:20

标签: ruby hash

我经常写这样的东西:

a_hash['x'] ? a_hash['x'] += ' some more text' : a_hash['x'] = 'first text'

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

5 个答案:

答案 0 :(得分:30)

有两种方法可以为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"

另一种初始化方法是传递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"

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

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

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

答案 1 :(得分:5)

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

a_hash = { 'x' => 'first text' }
// ...
a_hash['x'] << ' some more text'

答案 2 :(得分:1)

由于您使用哈希来收集字符串,我假设您只是想确保在追加时不会出现错误。因此,我将哈希默认为空字符串。然后,无论是否使用哈希键,都可以无错误地附加。

a_hash = Hash.new {|h,k| h[k]=""}

texts = ['first text', ' some more text']

texts.each do |text|
  a_hash['x'] << text
end

puts a_hash['x'] #=> 'first text some more text'

答案 3 :(得分:0)

Hash的构造函数在其第一个参数中具有键的默认值。这样

>> a_hash = Hash.new "first text"
=> {}
>> a_hash['a']
=> "first text"
>> a_hash['b'] += ", edit"
=> "first text, edit"

答案 4 :(得分:0)

如果您不想弄乱default=值(现有哈希值),可以使用fetch(key [, default])作为具有默认值的查找来缩短代码:

a_hash['x'] = a_hash.fetch('x', 'first_text') + ' some more text'