massaus99 massaus99 - 5 months ago 8
Ruby Question

How can i display what number includes the three?

This code shows the 1000th number of a string that contains numbers from 1 to 999.The number putted by the code is 3. How can i modify the code to put the entire number where the 3 belongs?
Thank you all and sorry for my bad english :)

i = 1
megastringa = ""
while i != 1000 do
megastringa << i.to_s
i = i + 1
end
puts "#{megastringa}"
puts "This is the 1000th digit: #{megastringa[999]}"

Answer

There's a much easier way of doing what you're trying to achieve (without using loops)> replace your entire code with:

megastring = (1..999).to_a.join
puts "Entire string is #{megastring}"
puts "1000'th digit is #{megastring[999]}"
puts "first 1000 digits is: #{megastring[0..999]}"

However, if you're wanting the actual 3 digit answer, you do need loops and should be written as:

i = 1
megastringa = ""
while megastringa.length < 1000 do
   megastringa << i.to_s
   i = i + 1
end
puts "#{megastringa}"
puts "This is the 1000th digit: #{megastringa[999]}"
puts "This is the number which the 1000th digit appears #{i-1}"
Comments