【问题标题】:Ruby? How to ignore newlines in cut and pasted user input?红宝石?如何忽略剪切和粘贴的用户输入中的换行符?
【发布时间】:2009-03-03 12:11:57
【问题描述】:

我编写了一个需要用户输入的小 Ruby 脚本。我预计用户在需要长条目的数据输入过程中的某些时候可能会有点懒惰,并且他们可能会从另一个包含换行符的文档中剪切和粘贴。

我一直在玩Highline gem,非常喜欢它。我怀疑我只是在文档中遗漏了一些东西,但是有没有办法获得可变长度的多行输入?

编辑:问题在于换行符终止了该输入,并且换行符之后的字符最终成为下一个问题的输入。

【问题讨论】:

  • 我理解正确吗:您想用几个换行符从命令行捕获用户输入?
  • 有几个可能的换行符。是的。
  • rampion 的解决方案效果很好,但仍然存在风险,因为只要添加一个空白行,它就会关闭问题。看看它是否适合你。

标签: ruby highline


【解决方案1】:

这是作者在他的示例中使用的内容:(来自 highline-1.5.0/examples)

#!/usr/local/bin/ruby -w

# asking_for_arrays.rb
#
#  Created by James Edward Gray II on 2005-07-05.
#  Copyright 2005 Gray Productions. All rights reserved.

require "rubygems"
require "highline/import"
require "pp"

grades = ask( "Enter test scores (or a blank line to quit):",
              lambda { |ans| ans =~ /^-?\d+$/ ? Integer(ans) : ans} ) do |q|
  q.gather = ""
end

say("Grades:")
pp grades

HighLine::Question#gather 上的一般文档(来自 highline-1.5.0/lib/highline/question.rb)

# When set, the user will be prompted for multiple answers which will
# be collected into an Array or Hash and returned as the final answer.
#
# You can set _gather_ to an Integer to have an Array of exactly that
# many answers collected, or a String/Regexp to match an end input which
# will not be returned in the Array.
#
# Optionally _gather_ can be set to a Hash.  In this case, the question
# will be asked once for each key and the answers will be returned in a
# Hash, mapped by key.  The <tt>@key</tt> variable is set before each
# question is evaluated, so you can use it in your question.
#
attr_accessor :gather

这些似乎是您在图书馆中的主要选择。其他的,你必须自己做。

【讨论】:

  • 感谢斜坡。正是我想要的。不知道我是怎么忽略的。
【解决方案2】:

会不会是这样的:

input.gsub!('\r\n', '')

【讨论】:

  • 输入阶段之后。问题是文本中有换行符,控制台会跳转到下一个输入问题。
猜你喜欢
  • 2015-02-12
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多