gpt4 book ai didi

ruby - HashMap 方法

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

this tutorial 中的练习之一是:

Exploit the fact that map always returns an array: write a method hash_keys that accepts a hash and maps over it to return all the keys in a linear Array.

解决方法是:

def hash_keys(hash)
hash.map { |pair| pair.first }
end

但是,我无法理解上述方法为何有效。例如,我写了一个解决方案,如下所示:

def hash_keys(hash)
# Initialize a new array
result = Array.new

# Cycle through each element of the hash and push each key on to our array
hash.map { |x,y| result.push(x) }

# Return the array
result
end

我能理解为什么我的方法有效,但我不理解他们提出的解决方案。例如,他们甚至没有创建 Array 对象。他们没有返回任何东西。看起来他们只是列出了每个键/值元素数组中的第一个元素。

最佳答案

我认为您误解了 map 的要点。它不只是遍历给定的集合(这就是 each 的作用)——它创建一个数组,其中每个元素都是使用原始集合的相应元素调用 block 的结果。

您的解决方案可以(也应该)使用 each 而不是 map 来编写,因为您并没有真正使用 map 确实如此 - 您只是利用了它为给定集合中的每个元素调用一次它的 block 这一事实。

关于ruby - HashMap 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16281983/

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