Ruby输出读入文本文件

时间:2017-12-02 15:24:07

标签: ruby

我的代码输出有问题。 我加了出去,重新出去看看发生了什么...... 我试图添加如果line.length!= 0和line!= 0,以不打印空行, 但它不起作用.. 这是输出:

Going to open 'TextFile.rtf'
out
in

re-out
out
in

re-out
out
in

re-out
out
in

re-out
out
in

re-out
out
in

re-out
out
in

re-out
out
in
66666666
re-out
out
in
99999999
re-out
out
in

re-out
out
in
25252525
re-out
out
in
11111111
re-out

我的文本文件:

BABA66666666 Hd12 
HEAD99999999 HDAS   
HEAD25252525  A1234  
SSSS11111111 No12 

我的代码:

def HID_num(str)
    matchtemp = ""
    temp = str.split(" ")
    temp.map! do |element|
        matches = element.match(/\A[A-Z]{4}(\d{8})\z/)
        next unless matches
        matchtemp = matches[1]
    end.compact
    puts matchtemp
end

if ARGV.length != 1
    puts "We need exactly one parameter. The name of a file."
    exit;
end

filename = ARGV[0]
puts "Going to open '#{filename}'"

fh = open filename

while (line = fh.gets)
    puts "out"
    if(line.length != 0)
        puts "in"
     HID_num(line)
    end
    puts "re-out"
end

fh.close

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你的主要方法有点混乱:

def HID_num(str)
  matchtemp = ""
  temp = str.split(" ")
  temp.map! do |element|
    matches = element.match(/\A[A-Z]{4}(\d{8})\z/)
    next unless matches
    matchtemp = matches[1]
  end.compact
  puts matchtemp
end

由于您只想打印匹配,因此无需在此处使用mapcompact。你可以这样做:

def HID_num(str)
  str.split(" ").each do |element|
    matches = element.match(/\A[A-Z]{4}(\d{8})\z/)
    puts matches[1] if matches
  end
end

您的原始版本无法按预期工作,因为您仍在打印空字符串(matchtemp = ""),即使找不到匹配项也是如此。