Question

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
Was it helpful?

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

OTHER TIPS

You need to do some checks on your length. If length is less than 4, than length - 5 will return a negative number and your

str[0..(length-5)] + ...

line will be upset. For example. If you type "str", then your code will try to do:

length = 3

str[0..-2] + str[-1..3]

which doesn't make sense. Also, since you check for str == "q" at the end, this is likely also happening for "q". Move your check and break up in the block, and make sure you don't treat all strings as if they're going to be longer than 4 characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top