Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ruby代码中将数组索引更改为整数_Ruby_Arrays - Fatal编程技术网

在ruby代码中将数组索引更改为整数

在ruby代码中将数组索引更改为整数,ruby,arrays,Ruby,Arrays,通过这个命令,我可以得到数组索引,但我可以将这个索引用作整数 index=strInput.each_index.select{|i| strInput[i] == subInput}.map(&:to_i) puts (index) 打印输出时,以桶状[15]显示 当我尝试直接使用索引时,就像 puts scores[index] 它返回错误 `[]': can't convert Array into Integer (TypeError) 如何将索引转换为整数 Ps

通过这个命令,我可以得到数组索引,但我可以将这个索引用作整数

index=strInput.each_index.select{|i| strInput[i] == subInput}.map(&:to_i)
    puts (index) 
打印输出时,以桶状[15]显示

当我尝试直接使用索引时,就像

puts scores[index]
它返回错误

`[]': can't convert Array into Integer (TypeError)
如何将索引转换为整数

Ps.strInput={1,2,3,4,5}/子输入={3}

只要做就行了

 puts scores[index.first]
因为
索引
是一个数组。从你的尝试来看,在我看来,
分数
也是一个数组。您可以通过它的
整数
索引访问数组元素。但是您将它放入
索引中,它是一个
数组
,而不是一个
整数
索引。因此,您得到的错误是无法将数组转换为整数(TypeError)

你可以写

strInput.each_index.select{|i| strInput[i] == subInput}.map(&:to_i)
作为

因为调用了,所以将数组
strInput
的所有
整数
索引传递给该方法。因此,不需要最后调用part
map(&:to_i)

我将使用

strInput.each_index.select{|i| strInput[i] == subInput}
ind = strInput.index { |elem| elem == subInput }    
puts scores[ind]