arrays - 使用泛化的 map 方法通过返回多个结果来传递元素和阻塞
问题描述
我希望你能帮助我。我试图了解发生了什么,但这是我必须做的:
写一个广义的map和reduce方法。这两种方法都将占用一个块,并要求您在方法和块之间传递信息。
这是测试正在寻找的内容:
describe 'my own map' do
it "returns an array with all values made negative" do
expect(map([1, 2, 3, -9]){|n| n * -1}).to eq([-1, -2, -3, 9])
end
it "returns an array with the original values" do
dune = ["paul", "gurney", "vladimir", "jessica", "chani"]
expect(map(dune){|n| n}).to eq(dune)
end
it "returns an array with the original values multiplied by 2" do
expect(map([1, 2, 3, -9]){|n| n * 2}).to eq([2, 4, 6, -18])
end
it "returns an array with the original values squared" do
expect(map([1, 2, 3, -9]){|n| n * n}).to eq([1, 4, 9, 81])
end
end
到目前为止我的代码:
def map(element1)
element1.map { |n| n * -1 }
end
现在我没有进一步输入任何内容,因为我需要了解如何使用相同的方法来寻找不同的东西?
以下是错误:
my own map
returns an array with all values made negative
returns an array with the original values (FAILED - 1)
returns an array with the original values multiplied by 2 (FAILED - 2)
returns an array with the original values squared (FAILED - 3)
ArgumentError:
negative argument
# ./lib/my_code.rb:2:in `*'
# ./lib/my_code.rb:2:in `block in map'
# ./lib/my_code.rb:2:in `map'
# ./lib/my_code.rb:2:in `map'
# ./spec/generalized_map_and_reduce_spec.rb:10:in `block (2 levels) in <top (required)>'
感谢您查看,非常感谢您在正确方向上的任何帮助。
解决方案
你不应该Enumerable#map
用来实现你自己的map
.
- 使用
while
orfor
循环 or (这将是最好的解决方案)Enumerable#each
。 - 让您
map
接受一个块并在循环内调用此块或将其传递给each
推荐阅读
- python - 如何使用 Pandas 仅保留当前月份的数据?
- c# - 如何模拟 Func
? - opengl - 使用实例数据的顶点属性缓冲区或统一缓冲区进行实例化渲染
- javascript - 续集 INNER JOIN
- dependencies - 列出 maven 依赖项而不下载 jars
- javascript - SSE 似乎有时不会一直刷新到客户端 - 它与代理有关吗?
- powershell - 如何获取powershell日志
- python - 错误:只有整数标量数组可以转换为标量索引(初学者)
- java - 当 SEQUENCE 不存在时,避免在第一次启动应用程序时出现异常
- swift - 如何在 Swift 中处理线程同步