Kenny Duran Kenny Duran - 2 months ago 7
Ruby Question

How to make a number argument a variable?

How do I make a number argument a variable?

For example:

Snippet 1:

a_7 = a+6
letter_7 = alphabet.slice[a_7..a_7]

Snippet 2:

letter_7 = alphabet.slice[7..7]

I would like to make snippet 1 have the same outcome as snippet 2, with a variable as the arguments within
action. Is there a way to do this?


So your issue come from the fact that you are using the slice method without any arguments. You can not use [] with the slice method. To make this work, you need to change [] to ()

letter_7 = alphabet.slice(7..7)

This will actually return H as the result, because arrays index start at 0, so to get the 7th letter, you will need to slice at index 6.

letter_7 = alphabet.slice(6..6) #=> 'G'

Or, you can just use the [] method on the string itself.

letter_7 = alphabet[6] #=> 'G'

Of course, you can replace the index values with variables, as long as the variables are set to integers.

a = 6

letter_7 = alphabet[a] #=> 'G'