2014-01-21 51 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