我正在研究事件报告者 http://tutorials.jumpstartlab.com/projects/event_reporter.html帮助学习 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 >>
根据the docs http://ruby-doc.org/stdlib-2.1.1/libdoc/csv/rdoc/CSV.html,CSV 对象的行为基本上类似于常规 IO 对象。他们通过通读文件(通常是逐行)来跟踪文件中的当前位置。所以在你的第一个attendees.each
,您通读了整个文件。随后调用.each
将尝试读取下一行,但没有任何一行,因为我们已经位于文件末尾,因此您的循环不再执行。
您可以通过将底层 IO 实例倒回到文件的开头来修复此问题,使用#rewind http://ruby-doc.org/stdlib-2.1.1/libdoc/csv/rdoc/CSV.html#method-i-rewind。在您的具体情况下,请将其放在迭代参加者之后。
attendees.each do |attendee|
# ...
end
attendees.rewind
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)