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

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?


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

One liner hack sure. Graceful...well not exactly.

input = [(print 'Name: '), gets.rstrip][1]

I know this question is old, but I though I'd show what I use as my standard method for getting input.

require 'readline'

def input(prompt="", newline=false)
  prompt += "\n" if newline
  Readline.readline(prompt, true).squeeze(" ").strip
end

This is really nice because if the user adds weird spaces at the end or in the beginning, it'll remove those, and it keeps a history of what they entered in the past (Change the true to false to not have it do that.). And, if ARGV is not empty, then gets will try to read from a file in ARGV, instead of getting input. Plus, Readline is part of the Ruby standard library so you don't have to install any gems. Also, you can't move your cursor when using gets, but you can with Readline.

And, I know the method isn't one line, but it is when you call it

name = input "What is your name? "