开发者

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

开发者 https://www.devze.com 2022-12-31 22:02 出处:网络
Often I find myself doing t开发者_高级运维he following: print \"Input text: \" input = gets.strip

Often I find myself doing t开发者_高级运维he 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? "


Following @Bryn's lead:

def prompt(default, *args)
  print(*args)
  result = gets.strip
  return result.empty? ? default : result
end


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


I found the Inquirer gem by chance and I really like it, I find it way more neat and easy to use than Highline, though it lacks of input validation by its own.
Your example can be written like this

require 'inquirer'
inputs = Ask.input 'Input text'
0

精彩评论

暂无评论...
验证码 换一张
取 消