我剛剛開始使用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