没有将Array隐式转换为Integer

没有将Array隐式转换为Integer

我创建了一个简单的方法,可以对字符串中的字符进行排序,如果“b”在“a”之后的三个(或更少)字符内,则返回true,反之亦然。
下面是:

def near_ab(string)
  arr = string.split("")
  a_position = arr.each_with_index.select {|i| arr[i] == "a"}
  b_position = arr.each_with_index.select {|i| arr[i] == "b"}

  if a_position - b_position <= 3      #arr[a] - arr[b] == 3
     return true
 else
     return false
 end

结束
但是,在运行之后,我得到以下错误:
    `[]': no implicit conversion of Array into Integer (TypeError)

为什么它会给我这个错误,我应该如何解决它?

最佳答案

方法each_with_index将第二个参数映射为索引。
改用这个:

arr.each_with_index.select {|element, i| arr[i] == "a"}

一个更好的方法来实现你想要的:
def near_ab(string)
  arr = string.split("")
  a_position = arr.index('a') # Array#index returns the index of the first element that match `'a'` in this case
  b_position = arr.index('b')

  if (a_position - b_position).abs <= 3      #arr[a] - arr[b] == 3
    return true
  else
    return false
  end
end

near_ab('hallo, ich bin Jonas!') # => returns false

(您可以复制粘贴到您的控制台中进行尝试)

关于ruby-on-rails - 没有将Array隐式转换为Integer(TypeError),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33619193/

10-10 14:50