Often I find myself doing the following:
print "Input text: " input = gets.strip
Is there a graceful way to do this in one line? Something like:
puts "Input text: #{input = gets.strip}"
The problem with this is that it waits for the input before displaying the prompt. Any ideas?
In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished. puts "My name is #{name}!"
Ruby has another three methods for printing output. In the example, we present the p , printf and putc methods. The p calls the inspect method upon the object being printed. The method is useful for debugging.
chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.
open Method. You can use File. open method to create a new file object and assign that file object to a file.
I think going with something like what Marc-Andre suggested is going to be the way to go, but why bring in a whole ton of code when you can just define a two line function at the top of whatever script you're going to use:
def prompt(*args) print(*args) gets end name = prompt "Input name: "
Check out highline:
require "highline/import" input = ask "Input text: "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With