我对Ruby很新,我认为如果陈述是直观的,但显然我错过了一些东西。
我有一个.xls文件,我正在阅读电子表格gem。 该文件如下所示:
从第2行开始(有三列)(第1行包含标题 - 用户名,ID,计数):
bob abc 1
bob abc 2
bob abc 3
bob abc 4
kevin abc 5
kevin abc 6
kevin abc 7
ciara abc 8
ciara abc 9
ciara abc 10
kate abc 11
kate abc 12
kate abc 13
我有以下代码来确定有多少用户:
def self.number_of_users
_sheet = @book.worksheet(0)
_reference_row = _sheet.row(1) #rows are zero index based in spreadsheet gem
@users += 1 #initialized to 0 at beginning of class
_sheet.each 1 do |row| #starting the do each at row 2 of .xls
if row[0] != _reference_row[0] #[] for column access
@users += 1
puts row[0] #print statements for check
puts _reference_row[0] #...
end
end
puts @users
end
而不是最后打印4,我得到10!我很困惑。
答案 0 :(得分:1)
在您的代码中,引用[0]保持' bob'。更新reference_row。
def self.number_of_users
_sheet = @book.worksheet(0)
_reference_row = _sheet.row(1) #rows are zero index based in spreadsheet gem
@users += 1 #initialized to 0 at beginning of class
_sheet.each 1 do |row| #starting the do each at row 2 of .xls
if row[0] != _reference_row[0] #[] for column access
@users += 1
_reference_row = row ### UPDATE _reference_row here
puts row[0] #print statements for check
puts _reference_row[0] #...
end
end
puts @users
end
或者你可以这样做。它更像是Ruby方式。
def self.number_of_users
sheet = @book.worksheet(0)
puts sheet.row(1..-1).map(&:first).uniq.count
end