Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby与Python的setDefault()等价于什么?_Python_Ruby On Rails_Ruby - Fatal编程技术网

Ruby与Python的setDefault()等价于什么?

Ruby与Python的setDefault()等价于什么?,python,ruby-on-rails,ruby,Python,Ruby On Rails,Ruby,我知道Python有一个setDefault函数,允许您为缺少的值设置值。然而,我很好奇这将如何移植到Ruby 特别是这样一个例子: animals = Animal.objects animal_names = {} for animal in animals: a = animal_names.setdefault(animal.name, []) a.append({'color': animal.color, 'size': animal.size}) 我想我可以在

我知道Python有一个setDefault函数,允许您为缺少的值设置值。然而,我很好奇这将如何移植到Ruby

特别是这样一个例子:

animals = Animal.objects

animal_names = {}

for animal in animals:
    a = animal_names.setdefault(animal.name, [])
    a.append({'color': animal.color, 'size': animal.size})

我想我可以在编写Ruby时使用它,但需要完全掌握这个概念。我想这个例子会让我明白。

Ruby有hash.fetch方法,您可以用同样的方法优雅地处理缺少的键,区别在于它不会存储这些值:

h = {}
value = h.fetch(:some_key, [])  
# value is now []
我们在Ruby中完成工作的另一个常见方法是:

h[:some_key] ||= []
或者我想如果你想将其赋值,你甚至可以这样做:

value = h[:some_key] ||= []

对于非Python读者来说,这段代码做了什么?这确实是一个重复,但答案也是错误的。我在以前的文章中添加了一个更详细的示例。我在这里还发布了一个更简单的示例。默认值的作用并不完全相同。默认值现在将该值分配给任何缺少的键。在Python中,它只会将其分配给特定的键。您仍然可以通过将proc传递给default来实现这一点,但我认为这太过分了。
h = Hash.new
h.default = "123"
puts h[any_key] //Prints 123