0
votes

I'm trying to assign a number to each letter of the alphabet and print strings using the numbers 0 through 25.

Creating array: alphabet = ('A'..'Z').to_a

Printing array: puts alphabet[6,8].join gives me an output of GHIJKLMN, which is not what I was expecting. Expectation is for it to print: GI

Additionally, if I try: puts alphabet[6,8,15].join I get the following error: wrong number of arguments (given 3, expected 1..2) (ArgumentError)

I am using Ruby 2.3.1. What am I doing wrong?

2
What are you trying to accomplish with the [6,8,15] syntax? - AShelly
I'm attempting to print any word. Let's say I wanted to print "CHEESE" - Mike D
It would be helpful if you could explain what, precisely, is unclear to you in the documentation of Array#[]. That way, the Ruby developers can improve the documentation so that future developers do not stumble on the same roadblocks that you did. - Jörg W Mittag

2 Answers

4
votes

Array#[] is quite versatile. You can pass an index:

alphabet[6] #=> "G"

an index and a length:

alphabet[6, 2] #=> ["G", "H"]

or a range:

alphabet[6..8] #=> ["G", "H", "I"]

If you want to fetch the values for multiple indices, there's values_at:

alphabet.values_at(6, 8, 15)
#=> ["G", "I", "P"]

which also supports ranges:

alphabet.values_at(6..8, 15)
#=> ["G", "H", "I", "P"]

or repeating the same index:

alphabet.values_at(2, 7, 4, 4, 18, 4)
#=> ["C", "H", "E", "E", "S", "E"]
3
votes

You can use #values_at to get the array's values at multiple indexes:

alphabet = ('A'..'Z').to_a
alphabet.values_at(2, 7, 4, 4, 18, 4).join

#=> "CHEESE"

Hope this helps!