Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner in Ruby for displaying a prompt, getting input, and assigning to a variable?

Tags:

ruby

input

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?

like image 858
Jarsen Avatar asked May 22 '10 20:05

Jarsen


People also ask

How do I prompt a user for input in Ruby?

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}!"

How do I print output in Ruby?

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.

What is the use of gets chomp in Ruby?

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.

Which one among the following method is used to open a file in Ruby?

open Method. You can use File. open method to create a new file object and assign that file object to a file.


2 Answers

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: " 
like image 104
Bryn Avatar answered Sep 19 '22 17:09

Bryn


Check out highline:

require "highline/import" input = ask "Input text: " 
like image 43
Marc-André Lafortune Avatar answered Sep 21 '22 17:09

Marc-André Lafortune