views:

170

answers:

3

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?

+3  A: 

Check out highline:

require "highline/import"
input = ask "Input text: "
Marc-André Lafortune
A: 

The problem with your proposed solution is that the string to be printed can't be built until the input is read, stripped, and assigned. You could separate each line with a semicolon:

$ ruby -e 'print "Input text: "; input=gets.strip; puts input'
Input text: foo
foo
maerics
That is not really one-line; you are using semicolons and that would probably not fit the graceful part of his request.
mathepic
Lars Haugseth
+3  A: 

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: "
Bryn
Indeed, that will work fine too. Until you want to add some input checking. Or some default value. Or not show what's typed because you ask for a password...
Marc-André Lafortune