Question About "Gets" in Ruby

Asking a user multiple questions using Ruby gets.chomp method

Instead of a while loop, I'd suggest to use loop do and break in case the name is empty (or also cohort):

loop do 
puts "Please enter the names of the students"
name = gets.chomp
break if name.empty?
puts "Please enter the cohort"
cohort = gets.chomp
# break if cohort.empty?
students << {name: name, cohort: cohort}
end

How to use gets and gets.chomp in Ruby

gets lets the user input a line and returns it as a value to your program. This value includes the trailing line break. If you then call chomp on that value, this line break is cut off. So no, what you have there is incorrect, it should rather be:

  1. gets gets a line of text, including a line break at the end.
    • This is the user input
  2. gets returns that line of text as a string value.
  3. Calling chomp on that value removes the line break

The fact that you see the line of text on the screen is only because you entered it there in the first place. gets does not magically suppress output of things you entered.

Ruby- gets issue

You can write your own Python equivalent input method:

def input(prompt)
print(prompt) # Output prompt
$stdout.flush # Flush stdout buffers to ensure prompt appears
gets.chomp # Get user input, remove final newline with chomp
end

Now we can try it:

name = input('What is your name? ')
puts "Welcome #{name}"

For more information on the methods used here. See these:

  • IO.flush
  • String.chomp

Check if a number entered by the user with gets.chomp is a float in ruby

puts "What are the first number you want to divide"
number1 = gets.chomp.to_i
=> 100
puts "What is the second number?"
number2 = gets.chomp.to_i
=> 3

# Regular math
result_a = number1 / number2
puts "#{number1} / #{number2} = #{result_a}"
=> 100 / 3 = 33 # Integer class persists...

# Use a ruby library instead! Numeric#divmod
result_b = number1.divmod(number2)
puts "Result: #{result_b}"
=> [33, 1] # [quotient, modulus]

How to timeout gets.chomp

You can use the timeout standard library

require "timeout"

puts "How are you?"
begin
Timeout::timeout 5 do
ans = gets.chomp
end
rescue Timeout::Error
ans = nil
end
puts (ans || "User did not respond")

Read more about the library http://www.ruby-doc.org/stdlib-2.1.5/libdoc/timeout/rdoc/Timeout.html

Can you include `gets.chomp` in a variable with a prompt?

You could wrap them in a method:

def ask_for_input
prompt = "> "
puts prompt
gets.chomp
end

input = ask_for_input # both prints a prompt and reads input


Related Topics



Leave a reply



Submit