rubyhighline

Ruby? How to ignore newlines in cut and pasted user input?


I've written a little Ruby script that requires some user input. I anticipate that users might be a little lazy at some point during the data entry where long entries are required and that they might cut and paste from another document containing newlines.

I've been playing with the Highline gem and quite like it. I suspect I am just missing something in the docs but is there a way to get variable length multiline input?

Edit: The problem is that the newline terminates that input and the characters after the newline end up as the input for the next question.


Solution

  • Here's what the author uses in his example: (from 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
    

    General documentation on HighLine::Question#gather (from 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
    

    These seem to be your main options w/in the library. Anything else, you'd have to do yourself.