Home > Mobile >  won't print out all of the strings
won't print out all of the strings

Time:09-16

I am in a coding bootcamp so I am really brand new to all of this and I was wondering why when I run this code it will only print the first two spots of the array?

words = ["Hello", "Goodbye", "Yes", "No"]

index = 0.to_i
while index.to_i < words.length
  p words[index.to_i]
  index = index.to_s   1.to_s
end

CodePudding user response:

It's because of

index = index.to_s   1.to_s

to_s converts the receiver to a string, i.e. 0 becomes "0" and 1 becomes "1". Calling on strings concatenates them, i.e. "0" "1" becomes "01".

That one is fine, because "01".to_i is still 1. However, on the next iteration you get "01" "1" which becomes "011" and "011".to_i is 11 which is more than the array's length.

To fix your code, you just have to remove the conversion and stick to integers:

words = ["Hello", "Goodbye", "Yes", "No"]

index = 0
while index < words.length
  p words[index]
  index = index   1
end

You can also let Ruby handle the index for you via each_index:

words.each_index do |index|
  p words[index]
end

or without an index via each:

words.each do |word|
  p word
end

CodePudding user response:

I don't know Ruby so I'm not sure about syntax. But I can solve your logic.

words = ["Hello", "Goodbye", "Yes", "No"]

index = 0.to_i
while index.to_i < words.length
  p words[index.to_i]
  index = index.to_i   1
end

This shall work. Logic is this :

  1. while index is less than length keep looping
  2. print words[index]
  3. increment index by 1 so that it moves to next position.
  •  Tags:  
  • ruby
  • Related