gpt4 book ai didi

ruby-on-rails - ruby block (产量)

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

我刚刚开始使用 Ruby,我在 Bloc 的类(class)中​​已经走了很长一段路,但现在我被困在与 yield 和 blocks 有关的练习上(我发现这是迄今为止最难掌握的概念说到学习 ruby​​)。

以下是纯格式文本所需的规范:

  • 定义一个 new_map 方法
  • 它应该接受一个数组作为参数,并返回一个根据作为 block 传入的指令修改的新数组。
  • 您不得使用 .map 或 .map!方法
  • 但是,请随意在方法中使用 each
  • 您需要将每个 block 调用的返回值存储在一个新数组中
  • 它应该映射任何对象

以下是需要满足的 RSpecs:

describe "new_map" do
it "should not call map or map!" do
a = [1, 2, 3]
a.stub(:map) { '' }
a.stub(:map!) { '' }

expect( new_map(a) { |i| i + 1 } ).to eq([2, 3, 4])
end

it "should map any object" do
a = [1, "two", :three]
expect( new_map(a) { |i| i.class } ).to eq([Fixnum, String, Symbol])
end
end

这是他们给我的原始 def 方法:

def new_map(array)
new_array = []
array.each do |item|
# invoke the block, and add its return value to the new array
end
end

然后这是我当前的代码(更新):

def new_map(a)
new_array = []
a.each do |item|
# invoke the block, and add its return value to the new array.
yield(item, new_array)
end
end

a = [2, 3, 4]

new_map(a) do |i, e|
e << i
end

最后,当我提交我刚刚列出的当前代码时,我收到以下错误(已更新):

new_map should not call map or map! (INCOMPLETE)

    expected: [2, 3, 4]
got: [1, 2, 3]

(compared using ==)
exercise_spec.rb:9:in `block (2 levels) in <top (required)>'

new_map should map any object (INCOMPLETE)

expected: [Fixnum, String, Symbol]
got: [1, "two", :three]

(compared using ==)

exercise_spec.rb:14:in `block (2 levels) in <top (required)>'

最佳答案

您没有意识到 yield 可以返回一个值。 block 中最后执行的语句是返回值。

因此您可以从每个 yield 调用中获取结果并将其添加到结果数组中。

然后,将生成的数组作为 new_map 方法的返回值。

def new_map(a)
new_array = []
a.each do |item|
# invoke the block, and add its return value to the new array.
new_array << yield(item)
end
new_array
end

关于ruby-on-rails - ruby block (产量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132181/

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