2015-05-08 34 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 

這不會通過所有測試,但最後一步應該是可行的。