rubygetsputs

Ruby- gets issue


I'm currently in the process of learning ruby, and I don't know if I'm doing something wrong or the compiler is, but this code:

puts "Name?"
name = gets
puts "Welcome " + name

Outputs:

#blank line waiting for input, if gotten input
Prints input, Name? And Welcome Name

I want it to do something like python's input("Name? ")


Solution

  • 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: