2014-01-21 43 views
0

从这个命令,我可以得到数组索引,但我可以使用该索引作为整数更改数组索引到整数红宝石代码

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}/subInput = {3}

回答

1

只要做

puts scores[index.first] 

因为index是一个数组。看看你的尝试,我认为scores也是一个数组。 Arrays are ordered, integer-indexed collections of any object。您可以通过它所具有的Integer索引访问数组元素。但你把它放到index这是一个Array,而不是一个Integer指数。所以你得到的错误为无法将数组转换为整型(TypeError)

你可以把它写

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

strInput.each_index.select{|i| strInput[i] == subInput} 

因为你叫Array#each_index,所以你传递数组strInput的所有Integer指数的方法,Array#select。因此不需要最后的电话map(&:to_i)

我会写你的代码,如下使用Array#index

ind = strInput.index { |elem| elem == subInput }  
puts scores[ind] 
+0

这是work.Thank你。 – user3214044