ruby - 初始化哈希

标签 ruby hash

我经常写这样的东西:

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

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

最佳答案

有两种方法可以为 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 传递一个 block ,每次为没有值的键请求值时调用该 block 。这允许您为每个键使用不同的值。

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"

block 被传递了两个参数:要求值的散列和使用的键。这使您可以选择为该键分配一个值,以便每次给出特定键时都会显示相同的对象。

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

这最后一种方法是我最常使用的方法。它还可用于缓存昂贵计算的结果。

关于ruby - 初始化哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2990812/

相关文章:

java - 如何使用 flatmap java8 根据值的键数对 HashMap 进行排序?

Python哈希表设计

python - 如何在Python中定义哈希函数

ruby-on-rails - 如何将多行代码放入一个 format.html block 中?

ruby-on-rails - 将记录行返回到查看页面时 ActiveRecord 模型的奇怪行为

ruby-on-rails - 在 Ruby (Rails) 中模拟抽象类

Ruby String 类的多种方法和效率

ruby - 一个 Ruby 对象可以破坏另一个吗?

c# - 如何在 asp.net 身份中使用指定的盐和密码生成哈希?

security - TLS 足够安全吗?需要在 PA-DSS 支付应用程序中滚动哈希吗?