2017-09-23 108 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