2017-09-23 120 views
0

我有我下面的說明here麻煩線路紅寶石:不能從Array

array1.delete_at(i) 

我相信從數組刪除元素刪除元素,但我得到的一個奇怪「的隱式轉換字符串到整數「錯誤。任何幫助,將不勝感激。

def calc(input) 
    stack = [] 
    array1 = input.split(//) #// splits into individual characters 
    array1.each do |i| 
     if i.match(/[0-9]/) then 
      stack.push(i.to_i) 
      puts "\n" ; print stack 
      array1.delete_at(i) 
      puts "\n" ; print array1 
     end 
    end 
end 

string = calc('123456') 
puts string 
+0

快速調試:'p stack'或'p array1'。 – tadman

回答

0

i是一個字符串,即使它包含數字

試試這個

array1.delete_at(i.to_i) 
+0

代碼現在運行..謝謝! –

0

我想你想使用each_with_index而非each,這樣你就可以通過該索引值到delete_at。目前,您從input傳遞一個數字作爲要從字符串中刪除的索引,這看起來並不像您想要的那樣。

我認爲下面會爲你工作:

def calc(input) 
    stack = [] 
    array1 = input.split(//) 
    array1.each_with_index do |num, i| 
    if num.match(/[0-9]/) then 
     stack.push(num.to_i) 
     puts; print stack 
     array1.delete_at(i) # passing the index rather than num now 
     puts; print array1 
    end 
    end 
end 

注意,我改變到puts,因爲當不帶參數調用puts將添加一個新行。

+0

謝謝加里。我試過你的代碼,但刪除,從數組中刪除每個匹配值的對象。我只想刪除特定的值! –

+0

@BillBisco明白了 - 我已經更新了我的答案。 – garythegoat

0

正如其他海報指出的,i是一個字符串。改爲:

array1 = input.split(//).map(&:to_i) 
+0

謝謝。我喜歡你要去哪裏看起來更有效率。但是,我現在從該語法中得到一個錯誤。 22:在'calc in block'中:未定義的方法'匹配'爲1:整數(NoMethodError) –

+0

'整數'沒有一個叫'匹配'的函數。這些僅適用於字符串。當我寫這個時,我不知道輸入是什麼。我會爲你的用例使用Ursus解決方案。 – davorb