Ruby CSV.each in while循环没有执行第二次

时间:2014-05-12 06:24:12

标签: ruby

我正在研究EventReporter项目以帮助学习Ruby。

这是我到目前为止所得到的:

require 'CSV'

puts 'Welcome to Event Reporter!'
print 'Enter command: '
command = gets.chomp

def clean(attribute, type)
    if (type == 'regdate')
    elsif (type == 'first_name')
    elsif (type == 'last_name')
    elsif (type == 'email_address')
    elsif (type == 'homephone')
        homephone = attribute
        homephone = homephone.to_s.gsub(/\D/, '')
        if (homephone.length < 10)
            homephone = '0000000000'
        elsif (homephone.length == 11)
            if (homephone[0] == '1')
                homephone[0] = ''
            else
                homephone = '0000000000'
            end
        elsif (homephone.length > 11)
            homephone = '0000000000'
        end
        return homephone
    elsif (type == 'street')
    elsif (type == 'city')
    elsif (type == 'state')
    elsif (type == 'zipcode')
        zipcode = attribute.to_s.rjust(5, "0")[0..4]
        return zipcode
    end
    return attribute
end

queue = []
while (command != 'q') do
    command = command.split
    if (command[0] == 'load')
        command[1] ? filename = command[1] : filename = 'event_attendees.csv'
        attendees = CSV.open filename, headers: true, header_converters: :symbol
        puts "Loaded #{filename}"
    elsif (command[0] == 'find')
        attribute = command[1]
        criteria = command[2]

        # REACHES HERE SECOND TIME AROUND
        puts "#{command[0]} #{command[1]} #{command[2]}"

        attendees.each do |attendee|
            # ISNT REACHING HERE SECOND TIME AROUND
            puts 'TEST'

            # get cleaned attendee attribute
            attendee_attribute = clean(attendee[attribute.to_sym], attribute)
            # see if it matches the criteria input
            if criteria.to_s.downcase.strip == attendee_attribute.to_s.downcase.strip
                # if it does, add the attendee to the queue
                puts 'Match!'
                queue << attendee
            end
        end
    end
    print 'Enter command: '
    command = gets.chomp
end

attendees.each似乎没有通过while循环第二次执行。这是为什么?

~/practice/event_manager >>  ruby 'lib/event_reporter.rb'
Welcome to Event Reporter!
Enter command: load
Loaded event_attendees.csv
Enter command: find zipcode 11111
find zipcode 11111
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
Enter command: find zipcode 11111
find zipcode 11111
Enter command: q
~/practice/event_manager >>  

1 个答案:

答案 0 :(得分:4)

根据the docs,CSV对象的行为基本上类似于常规IO对象。它们通过逐行读取来跟踪它们在文件中的当前位置。因此,在您的第一个attendees.each上,您将阅读整个文件。对.each的后续调用将尝试读取下一行,但由于我们已经在文件的末尾,因此没有任何调用,因此您的循环不再执行。

您可以使用#rewind将基础IO实例倒回到文件的开头来解决此问题。在您的具体情况下,在迭代参与者之后将其放置。

attendees.each do |attendee|
  # ...
end
attendees.rewind