2009-03-03 23 views
2

我寫了一個需要一些用戶輸入的小Ruby腳本。我預計用戶可能在數據輸入期間的某個時間點需要很長時間的輸入,並且他們可能從包含換行符的另一個文檔中剪切和粘貼。Ruby?如何忽略剪切和粘貼用戶輸入中的換行符?

我一直在玩Highline寶石,很喜歡它。我懷疑我只是缺少文檔中的東西,但有沒有辦法獲得可變長度多行輸入?

編輯:問題是換行符終止輸入,並且換行符後面的字符最終成爲下一個問題的輸入。

+0

我的理解是否正確:您是否想用幾條換行符從命令行捕獲用戶輸入? – aivarsak 2009-03-03 14:33:07

+0

有幾個可能的換行符。是。 – srboisvert 2009-03-03 14:35:20

+0

rampion的解決方案效果很好,但仍存在風險,因爲只要添加一條空白行就會結束該問題。看看它是否適合你。 – aivarsak 2009-03-03 14:46:26

回答

5

下面是筆者在他的例子使用:(從高架-1.5.0 /例)

#!/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 

這些似乎是你的m ain選項w /在圖書館。別的,你必須自己做。

0

豈不是這樣的:

input.gsub!('\r\n', '') 
相關問題