Hong Kim February 2016

ruby ending methods other than end

awords = []
word = "x"

puts "Type as many words as you want, or press \"enter\" to quit."
while word != ""enter code here
  #get word from user
  word = gets.chomp
  if word == ('')
    puts 'you input nothing'
  end

  #add to array
  awords.push word 
end



#user exited loop test for array before printing

puts "Now sorting what you typed.. thanks."
puts awords.sort

Everything works fine, but I want this program to skip last two "puts" if users don't input anything. Is there anyway I could just stop program after puts 'you input nothing' if users decide not to input but press enter?

Answers


Dbz February 2016

If you don't want to puts the last two lines, then you should check to make sure there are values within awords.

awords = []
word = 'x'

puts "Type as many words as you want, or press \"enter\" to quit."
until word.empty?
  word = gets.chomp
  if word.empty?
    puts 'you input nothing'
  end

  awords << word
end


# Check to make sure awords has values in it
unless awords.empty?
  puts "Now sorting what you typed.. thanks."
  puts awords.sort
end

Now the easiest way to stop the program early if no input was ever given is to add a line after puts 'you input nothing' with a return.

puts 'you input nothing'
return if awords.empty?

You'll notice that I changed a lot of your == '' methods to .empty? because that is the ruby way of doing that type of check with strings.


Hong Kim February 2016

awords = []
word = 'x'

puts "Type as many words as you want, or press \"enter\" to quit."
until word.empty?
  word = gets.chomp
  if word.empty?
    puts 'you input nothing'
  end

  awords << word
end


# Check to make sure awords has values in it
unless awords.empty?
  puts "Now sorting what you typed.. thanks."
  puts awords.sort
end

thank you that was very clear

Post Status

Asked in February 2016
Viewed 3,163 times
Voted 4
Answered 2 times

Search




Leave an answer