Solved

def - sort_by

Posted on 2009-05-06
5
375 Views
Last Modified: 2012-05-06
Can someone tell me what is wrong with the sort_by? - see "def printfilelinedetails"
Trying to sort by column 3 - but not working.

Regards
Phil
require "csv"  
class CSVtest  
def initialize(filename)
   @filename = filename
   @results = CSV.read(@filename)
end 
def printfilelinedetails
   @results = File.open(@filename)                                        
   @results.each do |line|
   sorted = line.sort_by{|w|w[2]}   
   puts sorted
  end   
end
 
def printReferenceNos
    refnos = @results.find_all do |r|   
      r[1]=="Ref0001"  or r[1]=="Ref0002"
    end  
    puts "#{Time.now}\nFollowing reference numbers were selected:"  
    refnos.each {|m| puts "#{m[1]},#{m[2].downcase}"}  
end  
 
def sumcol3
    puts "the total of Man Hours Lost is: #{ @results.inject(0){|sum, line| sum + line[3].to_f}.to_s}"
    end
    
def selectVectusorSAP
   @results = File.open(@filename)                                        
   @results.each do |line|
     if line =~ /(vectus)|(sap)/i then
       line
   puts line
   end
  end   
end
 
phil = CSVtest.new("C:/RUBY_WORKING_MODELS/csv_master.txt")  
phil.printfilelinedetails
puts "\n"
phil.selectVectusorSAP
puts "\n"
phil = CSVtest.new("C:/RUBY_WORKING_MODELS/csv_master.txt")  
phil.printReferenceNos 
puts "\n"
phil.sumcol3
end

Open in new window

0
Comment
Question by:philsivyer
  • 3
  • 2
5 Comments
 
LVL 12

Expert Comment

by:cminear
ID: 24315339
You want to apply the 'sort_by' method directly to the @results variable.  The returned File instance is enumerable, by itself (which is why 'each' can be used, too).  When you applied the 'each' method, each line is a String, so when you then use 'sort_by', you are trying to sort the line, in-place, which you then print out.  (And because you are accessing an array index, you aren't getting what you want, obviously.)

You also say you want to sort by _column_ 3; the current code (opening the file with File.open) would sort by the 3rd character column, not the 3rd CSV column.  Furthermore, you are essentially overwriting the @results instance variable that was set during initialization, which you may not want to do.

I believe the code snippet below contains a corrected 'printfilelinedetails' method.  Note that the sorting of the results is immediately passed to 'each' to be outputted, and that we "rebuild" the line.  (If you really want the line as it originally is in the file, and hence use the 'File.open', then you need to perform the splitting yourself in the 'sort_by' method call.)  'sort_by' does not alter the contents of the @results variable, meaning @results if used again is still unsorted.
def printfilelinedetails
  #@results = File.open(@filename)                                        
  @results.sort_by {|line|
    line[2]  
    # line[2].to_i  (if you want to sort by number)
    # line[2].to_lower (if you want to sort alphabetically)
  }.each {|line_set|
    puts line_set.join(",")
  }
end

Open in new window

0
 

Author Comment

by:philsivyer
ID: 24323911
Hello
Thanks for the response - still strugling with the sort_by logic. Can I try a new approach - assume my file is as follows:
COL_A, COL_B,COL_C
A,          2,          SS
C,          1,           XX
B,          24,         123
what is the code for sorting by Col_b then Col_a then Colc?

Regards


0
 
LVL 12

Accepted Solution

by:
cminear earned 500 total points
ID: 24325968
Assuming @results is still being initialized with a 'CSV.read', take a look at this code snippet.

Building the array of the items in the order that you want precedence orders how the sorting is done.  Based on your example, I made a point of changing the second column to integers for the comparison, and forcing the first column to be lower-case.  This way '123' does not appear before '2' and 'B' would not appear before 'a'. Because the last column is a mix of strings and numbers, I just leave it as is.

One thing I forgot to mention is that if you are dealing with CSV files in Ruby, to take a look at FasterCSV (http://fastercsv.rubyforge.org/).  As the name implies, it works to be much faster than the standard CSV class.  Of course, if you are using Ruby 1.9.x, FasterCSV has replaced the original CSV class implementation, so you already have it.  (If you are dealing with small files and/or just learning, there is no reason to change anything just yet.  I'm throwing it out there just as an FYI.  Plus, the sorting is done on an array, so parsing a CSV file more quickly doesn't help the sort speed at all.)
def printfilelinedetails
  @results.sort_by {|line|
    [ line[1].to_i, line[0].to_s.to_lower, line[2] ]  
  }.each {|line_set|
    puts line_set.join(",")
  }
end

Open in new window

0
 

Author Comment

by:philsivyer
ID: 24326364
cminear
Thanks for this - works a treat

Regards
Phil
0
 

Author Closing Comment

by:philsivyer
ID: 31578433
Good work - thanks for prompt reply
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question