Edit: All fixed now. Beginners mistake but I thought I had troubleshot well enough for my beginners level. However I failed to remember the most basic thing to check.
I’m trying to find the location of X within an array. According to a website it should work just like this:
a = [ "a", "b", "c" , "d"]
a.index("d")
However this does not return anything on its own. However I’ve added an if statement to it:
a = [ "a", "b", "c" , "d"]
if a.index("d") == 3
puts "ok"
else
puts "error"
end
And this works. However obviously this isn’t optimal since I won’t be guessing between just 4 array elements but many thousands. Is the first code supposed to work? And if not how do I get the array number?
Secondary question: After searching for this value “d” (above code) and getting its position. How do I take the position information, put it into an integer so I can apply math to it. And then fetch the new array?
Additionally, it would also be best if the value being searched for can be controlled outside of this index. How do I make the index point to a string instead that contains what to search for?
Thanks and sorry I am completely new to programming. I am doing pretty good though so far.
It works for me.
What ruby version are you using (
ruby -v).My code (with ruby 1.9.3):
To get the ‘next’ element, e.g. to get the next 1 element after ‘b’:
Of oucrse “c” is at position 2 (zero based numbering for arrays) as you can see with