0

I initialize my array

my_array = Array.new(26)

and then try to populate it

my_array[0..25] = ["A".."Z"]
# => "A".."Z"

Same output when I try:

my_array[0..25] = "A".upto("Z")
# => "A".."Z"

When I try using a block:

my_array[0..25] = "A".upto("Z") { |l| l} #=> "A"
my_array
# => ["A"]

When after trying the first or second method of populating above, I inspect my_array:

my_array
# => ["A".."F"]

which I understand is an enumerator. So I try:

my_array.each {|l| p l}

but all I'm returned is

"A..F"
# => ["A".."F"]

What is actually being stored in the array?

How can I correctly implement the populating of the array with the letters of the alphabet?

2 Answers 2

1

Ruby actually has a method called to_a and you can convert a range to an array. So if I wanted a variable with all the letters of the alphabet using a range I could do alphabet = ('a'..'z').to_a. Also, ruby is dynamically typed and you do not need to initialize an array. a = [1,2,3] is all you need to do. You would not need to do

a = Array.new(3)
a = [1,2,3]
Sign up to request clarification or add additional context in comments.

1 Comment

So I basically needed to change the enumerator ('A..Z') to an array type. Dang! Wish I'd asked earlier. :) Thanks.
1
my_array = Array.new(26)

my_array[0..25] = ["A".."Z"]
#=> "A".."Z"

my_array.size
  #=> 1
my_array.first
  #=> "A".."Z"
my_array.first.is_a? Range
  #=> true

Had we initially written my_array = [] the results would have been the same.

The easiest way to obtain what you want is to splat the range:

my_array = []
my_array[0..25] = *"A".."Z"
  #=> ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
  #    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 

which is equivalent to

my_array[0..25] = "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                  "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"

but this can be done in a single operation:

my_array = *"A".."Z"
  #=> ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
  #    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.