代码之家  ›  专栏  ›  技术社区  ›  srboisvert

红宝石如何在剪切和粘贴的用户输入中忽略换行符?

  •  2
  • srboisvert  · 技术社区  · 17 年前

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

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

    编辑:问题是换行符终止输入,换行符后的字符作为下一个问题的输入。

    2 回复  |  直到 17 年前
        1
  •  5
  •   rampion    17 年前

    以下是作者在示例中使用的内容:(来自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
  •  0
  •   wombleton    17 年前

    这不是像:

    input.gsub!('\r\n', '')
    
    推荐文章