Use number from input to array access position

EDIT: first part removed, I found the answer.

I have the following problem: im reading a number from input and trying to use that number to access a given array position. I am getting the following results

value #=> "0"
value.to_i #=> 0
myArray[0] #=> MyObject
myArray[value.to_i] #=> nil

      

-1


a source to share


3 answers


This works for me.



irb(main):012:0> myArray = ['first']
=> ["first"]
irb(main):013:0> value = '0'
=> "0"
irb(main):014:0> myArray[value.to_i]
=> "first"

      

+4


a source


Try it myArray[Integer(value)]

(although value.to_i

works for me too):



>> value = "0"
=> "0"
>> myArray = ["a", "b"]
=> ["a", "b"]
>> myArray[0]
=> "a"
>> myArray[Integer(value)]
=> "a"

      

0


a source


Thanks for all your answers, I tried to access and mass within a class variable with:

@myclass.myarray[value]

      

when I made a getter method and accessed myarray inside the object, the error went away. If anyone can explain this behavior please let me know

0


a source







All Articles