Ruby:无法从数组中删除元素

时间:2017-09-23 13:06:36

标签: arrays ruby

我无法从

行的数组中删除元素
array1.delete_at(i)

我相信我遵循了here的说明,但我得到一个奇怪的“没有隐式转换字符串到整数”错误。任何帮助将不胜感激。

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

3 个答案:

答案 0 :(得分:0)

i是一个字符串,即使它包含数字

试试这个

array1.delete_at(i.to_i)

答案 1 :(得分: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 "\n"更改为puts,因为puts会在不带参数的情况下添加新行。

答案 2 :(得分:0)

正如另一张海报所说,i / width是一个字符串。这样做:

i