2015-05-08 251 views
3

我刚刚开始使用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)>' 
+0

正如它所说 - 当你调用'new_map(a)'时,'a'是未定义的。在调用new_map之前将其设置为初始值,例如一组数字。 –

+0

@ChrisHeald没有工作,我在方法定义和方法调用之间设置了'a = [1,2,3,4]',程序现在执行,但是我得到了'期待:[2,3,4 ] got:[]' –

+0

另外,也许可以更充分地考虑评论文本。步骤1)执行该块。步骤2)将其值添加到数组。 – user12341234

回答

1

你没有意识到的是产量可以返回一个值。块中最后执行的语句是返回的值。

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

然后,将结果数组作为您的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 
+0

非常感谢@SteveTurczyn的完美工作,我很感激。 –

0

new_array在定义new_map,这是一个不同的 “词法作用域” 创建的任何对象(不完全的)比您拨打new_map时所写的区块要多。基本上,new_map方法中的代码可以看到new_array,但块中的代码不能。解决此问题的一种方法可能是查看方法injecteach_with_object,该方法可以在new_map方法中替代each

1

尝试这种情况:

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

new_map(a) { |i| i + 1 } 

yield啄只是需要从阵列的每个元素,并运行它穿过块。这个实验代码只是打印结果;这些应该收集在一个数组中。不难:

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

这不会通过所有测试,但最后一步应该是可行的。