首页 > 解决方案 > 使用泛化的 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)>'

感谢您查看,非常感谢您在正确方向上的任何帮助。

标签: arraysrubydictionarymethods

解决方案


你不应该Enumerable#map用来实现你自己的map.

  1. 使用whileorfor循环 or (这将是最好的解决方案) Enumerable#each
  2. 让您map接受一个块并在循环内调用此块或将其传递给each

推荐阅读