Ruby散列等价于Python dict setdefault

gab*_*rtv 12 ruby python hash dictionary

在Python中,可以读取字典/散列键,同时将键设置为默认值(如果尚不存在).

例如:

>>> d={'key': 'value'}
>>> d.setdefault('key', 'default')
'value'                                          # returns the existing value
>>> d.setdefault('key-doesnt-exist', 'default')
'default'                                        # sets and returns default value
>>> d
{'key-doesnt-exist': 'default', 'key': 'value'}
Run Code Online (Sandbox Code Playgroud)

有没有相当于Ruby哈希?如果没有,Ruby中的惯用方法是什么?

ste*_*lag 9

哈希可以具有默认值或默认值Proc(当密钥不存在时调用).

h = Hash.new("hi")
puts h[123] #=> hi
# change the default:
h.default = "ho"
Run Code Online (Sandbox Code Playgroud)

在上面的情况下,哈希保持为空.

h = Hash.new{|h,k| h[k] = []}
h[123] << "a"
p h # =>{123=>["a"]}
Run Code Online (Sandbox Code Playgroud)

Hash.new([]) 因为相同的数组(与相同的对象相同)将用于每个键,所以不会有效.


Bas*_*man 5

不要在这里打败死马,但 setDefault 的行为更像是 fetch 对散列的作用。它的行为方式与默认对哈希的行为方式不同。一旦在散列上设置默认值,任何丢失的键都将使用该默认值。setDefault 不是这种情况。它仅存储一个缺失键的值,并且仅当它无法找到该键时才存储该值。整个存储新键值对的部分是它与 fetch 不同的地方。

同时,我们目前只做 setDefault 做的事情:

h = {}
h['key'] ||= 'value'
Run Code Online (Sandbox Code Playgroud)

Ruby 继续开车回家:

h.default = "Hey now"
h.fetch('key', 'default')                       # => 'value'
h.fetch('key-doesnt-exist', 'default')          # => 'default'
# h => {'key' => 'value'}
h['not your key']                               # => 'Hey now'
Run Code Online (Sandbox Code Playgroud)

Python:

h = {'key':'value'}
h.setdefault('key','default')                   # => 'value'
h.setdefault('key-doesnt-exist','default')      # => 'default'
# h {'key': 'value', 'key-doesnt-exist': 'default'}
h['not your key']                               # => KeyError: 'not your key'
Run Code Online (Sandbox Code Playgroud)

  • 当你给它一个 `default` 值时,Ruby 的 `fetch` 的行为更像 Python 的 [`get`](https://docs.python.org/2/library/stdtypes.html#dict.get)。`setdefault` 的优点是 *后续* 代码行可以假设它已经存在,并且可以假设 `dict` 不包含显式添加的键以外的任何键,这使得代码更清晰,更易于阅读和管理。 (2认同)