我刚刚开始使用Ruby,我很喜欢在集体课程中进入我的课程,但现在我被困在与屈服和块有关的练习中(我发现它是最难的至于在学习ruby时掌握的概念)。红宝石块(收益率)
下面是纯格式化文本所需的规格:
- 定义new_map方法
- 应该采取的阵列作为参数并返回根据传过来的块中的指令修改的新的数组。
- 您不能使用.map或.map!方法
- 然而,随意的方法中使用的每个
- 你会想从每个块调用返回的值存储在一个新的数组
- 应该映射任何对象
下面是需要被满足的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不应该调用map或map! (不完全)
expected: [2, 3, 4]
got: [1, 2, 3]
(compared using ==)
exercise_spec.rb:9:in `block (2 levels) in <top (required)>'
new_map应该映射
expected: [Fixnum, String, Symbol]
got: [1, "two", :three]
(compared using ==)
exercise_spec.rb:14:in `block (2 levels) in <top (required)>'
正如它所说 - 当你调用'new_map(a)'时,'a'是未定义的。在调用new_map之前将其设置为初始值,例如一组数字。 –
@ChrisHeald没有工作,我在方法定义和方法调用之间设置了'a = [1,2,3,4]',程序现在执行,但是我得到了'期待:[2,3,4 ] got:[]' –
另外,也许可以更充分地考虑评论文本。步骤1)执行该块。步骤2)将其值添加到数组。 – user12341234