Reputation: 83
From this command, I can get array index but I can use this index as integer
index=strInput.each_index.select{|i| strInput[i] == subInput}.map(&:to_i)
puts (index)
When in print output, it show with bucket like [15]
And when I try to use index directly like
puts scores[index]
It return error
`[]': can't convert Array into Integer (TypeError)
How I convert index to integer.
Ps. strInput={1,2,3,4,5} / subInput={3}
Upvotes: 0
Views: 1076
Reputation: 118271
Just do
puts scores[index.first]
Because index
is an array. Looking at your attempt it seems to me scores
is also an array. Arrays
are ordered, integer-indexed collections of any object. You can access the Array elements via the Integer
indexes it has. But you put into it index
which is an Array
, not the an Integer
index. So you got the error as can't convert Array into Integer (TypeError).
You could write it
strInput.each_index.select{|i| strInput[i] == subInput}.map(&:to_i)
as
strInput.each_index.select{|i| strInput[i] == subInput}
Because you called Array#each_index
, so you are passing all the Integer
indices of the array strInput
, to the method Array#select
. Thus there is no need of the final call of the part map(&:to_i)
.
I would write your code as below using Array#index
ind = strInput.index { |elem| elem == subInput }
puts scores[ind]
Upvotes: 1