lib/roo/generic_spreadsheet.rb in roo-0.8.2 vs lib/roo/generic_spreadsheet.rb in roo-0.8.3

- old
+ new

@@ -256,11 +256,11 @@ letters = letters[1..-1] end result end - # write the current spreadsheet to stdout or into a file + # write the current spreadsheet to stdout or into a file #TODO: refactoring --> GenericSpreadsheet def to_csv(filename=nil,sheet=nil) sheet = @default_sheet unless sheet if filename @@ -269,9 +269,88 @@ file.close else write_csv_content(STDOUT,sheet) end true + end + + # find a row either by row number or a condition + # Caution: this works only within the default sheet -> set default_sheet before you call this method + # (experimental. see examples in the test_roo.rb file) + def find(*args) # :nodoc + result_array = false + args.each {|arg,val| + if arg.class == Hash + arg.each { |hkey,hval| + if hkey == :array and hval == true + result_array = true + end + } + end + } + column_with = {} + 1.upto(last_column) do |col| + column_with[cell(@header_line,col)] = col + end + result = Array.new + #-- id + if args[0].class == Fixnum + rownum = args[0] + tmp = {} + 1.upto(self.row(rownum).size) {|j| + x = '' + column_with.each { |key,val| + if val == j + x = key + end + } + tmp[x] = cell(rownum,j) + } + result = [ tmp ] # row(rownum) + #-- :all + elsif args[0] == :all + if args[1].class == Hash + args[1].each {|key,val| + if key == :conditions + column_with = {} + 1.upto(last_column) do |col| + column_with[cell(@header_line,col)] = col + end + conditions = val + first_row.upto(last_row) do |i| + # are all conditions met? + found = 1 + conditions.each { |key,val| + if cell(i,column_with[key]) == val + found *= 1 + else + found *= 0 + end + } + # p self.row(i) if found > 0 + if found > 0 + tmp = {} + 1.upto(self.row(i).size) {|j| + x = '' + column_with.each { |key,val| + if val == j + x = key + end + } + tmp[x] = cell(i,j) + } + if result_array + result << self.row(i) + else + result << tmp + end + end + end + end # :conditions + } + end + end + result end protected def unzip(filename)