From: Rob Biedenharn Date: 2010-11-15T21:26:56+09:00 Subject: Re: FasterCSV On Nov 14, 2010, at 10:48 PM, Francisca Munhoz wrote: > Hi I'm learning Ruby, so I have a beginners question for you: > > How Can I sort attributes.values for similar order as csv_header? Just > consider that I already order by csv_header on my query but i did not > work. > > @custom_csv = User.find(:all, :select=>"name, lastname, address > " :order > => "name, lastname, address") > > csv_header = [name,lastname,address] > > csv_string = FasterCSV.generate do |csv| > > csv << csv_header > > @custom_csv.each do |v| > > csv << v.attributes.values > > end > > end > > Thanks in advance! Well, since you've already limited the attributes that ActiveRecord will see (assuming by your syntax that User is a model derived from ActiveRecord::Base), then v.attributes will be a hash that contains just those three key/value pairs. Your definition of the headers probably needs to be something like: csv_header = %w[ name lastname address ] but then the statement in the inner loop can be: csv << v.attributes.values_at(*csv_header) You can lookup the docs for Hash#values_at and the * is the "unary unarray" operator or the "splat" which places the elements of csv_header into the argument list separately. This is equivalent to: csv << v.attributes.values_at("name","lastname","address") If you have other questions that get more Rails-specific, I'd suggest jumping over to the rails list. http://groups.google.com/group/rubyonrails-talk?hl=en -Rob Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/