gpt4 book ai didi

ruby-on-rails - 没有将数组隐式转换为整数(TypeError)

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:45 25 4
gpt4 key购买 nike

我创建了一个简单的方法来对字符串中的字符进行排序,如果“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 - 没有将数组隐式转换为整数(TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33619193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com