#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2006
    Location
    Newcastle, Australia
    Posts
    68
    Rep Power
    9

    Can't test empty string and exit


    Hi

    i was reading the chris Pine book and in attempting an exercise I cannot solve how to push a word into an array unless the input is an empty enter stroke in which case I should be printing the array sorted.

    I have tried it 3 different ways clearly I am missing something, can you help put me in the right direction please.

    Version 1 - Doesn't terminate on empty line
    Code:
    puts "enter a word one per line."
    puts "enter a blank line if you want to end."
    puts " >"  
    word = gets.strip 
    wordList = []  
    wordList.push word until word.empty? == true 
    if word.empty? == true   
         puts wordList.sort 
    end
    Version 2 - terminates on any input
    Code:
    puts "enter a word one per line."
    puts "enter a blank line if you want to end."
    puts " >"  
    word = gets.strip 
    wordList = []  
    if word.empty? == true
     	wordList.push word 
    else 	
            puts wordList.sort end
    Version 3 - Also terminates on any input
    Code:
    puts "enter a word one per line."
    puts "enter a blank line if you want to end." 
    puts " >"  
    word = gets.strip 
    wordList = []  
    if word != ''
     	wordList.push word 
    else
     	puts wordList.sort end
    I am little confused at where I am going wrong.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2006
    Location
    Newcastle, Australia
    Posts
    68
    Rep Power
    9
    Here is a solution I have got working. if you know how it could work better let me know.

    Code:
    puts "Enter a word on a each new line."
    puts "Press a blank new line to exit" 
    puts "> "  
    word = gets.strip 
    wordList = [] 
    while word.length > 0
         wordList.push(word)
         puts "> "
         word = gets.strip 
    end  
    puts wordList.sort

IMN logo majestic logo threadwatch logo seochat tools logo