2016-12-05 59 views
0

有以下內容的txt文件:閱讀特定的行到一個數組 - 紅寶石

Anders Hansen;87442355;11;87 
Jens Hansen;22338843;23;11 
Nanna Kvist;25233255;24;84 

我想文件中搜索用戶輸入取一個特定的名稱後。然後將該行保存到數組中,通過「;」分割。不能讓它工作。這是我的代碼:

user1 = [] 
puts "Start by entering the full name of user 1: " 
input = gets.chomp 
File.open("userregister.txt") do |f| 
f.each_line { |line| 
    if line =~ input then do |line| 
    user1 << line.split(';').map 
+0

嘗試用'line.start_with?(input)'替換'line =〜input'。 – ndn

+0

這似乎工作,歡呼! – David

+0

想要逐行讀取文件時,請考慮使用[IO :: foreach](http://ruby-doc.org/core-2.3.0/IO.html#method-c-foreach):' IO.foreach(「userregister.txt」)do | line | ...結束。 (這通常寫成'File.foreach ...',這是因爲'File'是'IO'的子類)。foreach'很方便的一個原因是,如果沒有使用塊,它會返回一個枚舉器,可以鏈接到其他方法,例如'Enumerable'模塊中的方法。 –

回答

0

=~在紅寶石嘗試匹配正則表達式(反之亦然)的字符串。

'foo' =~ 'bar' # => TypeError: type mismatch: String given 

有更合適的字符串方法,而不是使用方法:在這裏,你有兩個字符串,它給出了一個錯誤使用它。在你的情況下,#start_with?完成這項工作。如果你想檢查後者是否作爲子字符串包含在某個地方(但不是必需的開頭),你可以使用#include?


如果你確實想利用正則表達式作爲用戶輸入(通常是一個壞主意),你可以將它從字符串轉換爲正則表達式:

line =~ /#{input}/ 
+0

如果有一個「Anders Hansonson」,接下來是「Anders Hanson」,你想要後者?可能是'/ \ A#{input}:/'並且不用'start_with?'選項。 –

+0

@CarySwoveland然後你可以讀取文件反向xd – ndn

0

望着文件格式,我實際上會使用Ruby CSV類。通過指定column separator;,您將獲得每行的數組。

require 'csv' 

input = gets.chomp 
CSV.foreach('userregister.txt', col_sep: ';') do |row| 
    if row[0].downcase == input.downcase 
    # Do stuffs with row[1..-1] 
    end 
end