Search code examples
rubyeclipseloopsbreakupcase

Loop won't break and string won't capitalize properly?


I am trying to get a simple Ruby program to run correctly.

I need it to take user input until the user types q for "quit". It also needs to capitalize the last four letters of the users input and, with input under four letters, to capitalize all letters.

It only works for input over four letters, and, when I type "quit", it gets a nil error.

See the code below.

I am using Eclipse with Ruby 2.0.

puts ("\n" * 10)

loop do

  puts "Please enter a word. (To quit type q.)"   # Gets the users input

  puts ("\n" * 3)               #Scroll the screen 3 times

  str = gets.chomp              #Collect the player's response

  puts ("\n" * 3)               #Scroll the screen 3 times

  length = str.length           # Counts length of string

  str = str[0..(length-5)] + str[(length-4)..length].upcase # Only makes last four letters of user input capitalized

  puts str                      # Shows on screen the user input with capitalized last four letters

  puts ("\n" * 3)               #Scroll the screen 3 times

  break if str == "q"

end

Solution

  • You need to pay attention to [] when you write code like this:

    str = str[0..(length-5)] + str[(length-4)..length].upcase
    

    If an index is negative, it is counted from the end of string. For example:

    str = "abcde"
    str[-1] # => "e"
    str[-2] #=> "d"
    

    See String.[] for more details.

    With regard to your question, here is my logic:

    break if str == "q"
    
    if str.length < 4
      str = str.upcase
    else
      str = str[0...-4] + str[-4..-1].upcase
    end
    p str