i } ) } end 它返回-6ren">
gpt4 book ai didi

Ruby range.reduce 与哈希累加器

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:27 26 4
gpt4 key购买 nike

我有这个方法

def heights
(60..68).reduce({}) { |h, i| h.merge!( { %(#{i/12}'#{i%12}") => i } ) }
end

它返回高度的哈希值

{
"5'0\"" => 60, "5'1\"" => 61, "5'2\"" => 62,
"5'3\"" => 63, "5'4\"" => 64, "5'5\"" => 65,
"5'6\"" => 66, "5'7\"" => 67, "5'8\"" => 68
}

这就是我想要的。但是,我不喜欢使用 merge! 方法。我更愿意使用 hash[key] = value 语法进行赋值:

def heights
(60..68).reduce({}) { |h, i| h[%(#{i/12}'#{i%12}")] = i }
end

但是这段代码会抛出错误。我知道使用 reduce,在你的管道中你可以命名你的累加器和元素。

我也明白了

sum = 0
(1..5).each { |i| sum += i }

相当于

(1..5).reduce(0) { |sum, i| sum + i }

为什么不这样

hash = {}
(1..5).each { |i| hash[i.to_s] = i }

工作方式与

相同
(1..5).reduce({}) { |hash, i| hash["#{i}"] = i }

最佳答案

你可以使用 each_with_object而不是 reduce:

(60..68).each_with_object({}) { |i, h| h[%(#{i/12}'#{i%12}")] = i }

enumerable.each_with_object(obj) { ... } 返回 obj 所以你不需要人工感觉 ; h 在您需要使用 reduce 的 block 中。

请注意, block 的参数顺序与 reduce 不同。

关于Ruby range.reduce 与哈希累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com