Append a a hash to a CSV in Ruby 1.8 - ruby

How to append to a array of hashes into CSV in Ruby 1.8. There is FasterCSV for Ruby 1.9 but how do I do in 1.8?
This is what I have tried. hasharray is an array which contains elements which are hashes.
CSV.open("data.csv", "wb") { |csv|
hasharray.each{ |oput|
oput.to_a.each {|elem| csv << elem}
}
}
This way puts all the data in the CSV but it puts them one below another instead of side-by-side.

When iterating over hashes, you want to use two arguments in the block, one for the key, the other for the value. Consider:
hasharray.each { |k,v| puts "#{k},#{v}" }

Related

sort ruby hash by specific key

I have a ruby hash like this
{"id"=>62, "name"=>"Wine and Spirits"}
{"id"=>63, "name"=>"Tobacco"}
{"id"=>64, "name"=>"Printing"}
{"id"=>65, "name"=>"Information Services"}
{"id"=>66, "name"=>"Business Supplies and Equipment"}
How do I sort this by name? I tried
categories.sort_by {|_key, value, _key1, value1| value1}
But that did not work
Assuming you want to sort an array of hashes:
def sort_by_name(hashes)
hashes.sort_by { |h| h["name"] }
end

flat_map in Ruby 1.8.7

Using Ruby 1.8.7, is there built-in functionality similar to Array.map which allows for the return of multiple values instead of just one? E.g. I have an array and each element contains an array - I want to end up with all values from the inner arrays. For instance, an array of states where each as an array of counties - I want a an array of ALL counties.
#states.map_many { |o| o[:states] }
Same as Array.flat_map in newer versions of Ruby. http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-flat_map
Just use array.map { ... }.flatten.
To get all counties, you'd use...
#counties = #states.map { |o| o[:states] }.flatten
If you wish to flatten by only one level (which flat_map does in current versions of Ruby), you can pass a 1 to flatten. This is unnecessary for your example, as you are building an array with at most two dimensions.

How can I use a ruby program to save an array of hashes to a csv file?

I have an array of hashes that contain sales data in a ruby program and would like to write code that would save this data to a csv file that I can later access or update. Any suggestions on how I can accomplish this? Thanks for any and all help!
You can use Ruby Marshal builtin class for serialization.
# load array from array.bin or initialize new array
array = if File.exists?('array.bin')
File.open('array.bin') do|file|
Marshal.load(file)
end
else
[]
end
# see what's in array
puts array.inspect
# modify array
array << ["test"]
# save into array.bin file
File.open('array.bin','w') do|file|
Marshal.dump(array, file)
end
I think you can consider using class CSV from Ruby standard library.
http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html

How to dump a 2D array directly into a CSV file?

I have this 2D array:
arr = [[1,2],[3,4]]
I usually do:
CSV.open(file) do |csv|
arr.each do |row|
csv << row
end
end
Is there any easier or direct way of doing it other than adding row by row?
Assuming that your array is just numbers (no strings that potentially have commas in them) then:
File.open(file,'w'){ |f| f << arr.map{ |row| row.join(',') }.join('\n') }
One enormous string blatted to disk, with no involving the CSV library.
Alternatively, using the CSV library to correctly escape each row:
require 'csv'
# #to_csv automatically appends '\n', so we don't need it in #join
File.open(file,'w'){ |f| f << arr.map(&:to_csv).join }
If you have to do this often and the code bothers you, you could monkeypatch it in:
class CSV
def self.dump_array(array,path,mode="rb",opts={})
open(path,mode,opts){ |csv| array.each{ |row| csv << row } }
end
end
CSV.dump_array(arr,file)
Extending the answer above by #Phrogz, while using the csv library and requiring to change the default delimiter:
File.open(file,'w'){ |f| f << arr.map{|x| x.to_csv(col_sep: '|')}.join }

Ruby: new array from one value in an array of objects

Forgive me if this has already been asked, I couldn't find it.
I have an array of objects, like:
[<#Folder id:1, name:'Foo', display_order: 1>,
<#Folder id:1, name:'Bar', display_order: 2>,
<#Folder id:1, name:'Baz', display_order: 3>]
I'd like to convert that array into an array just of the names, like:
['Foo','Bar','Baz']
and, while I'm at it it would be nice if I could use the same technique down the road to create an array from two of the parameters, ie name and display order would look like:
[['Foo',1],['Bar',2],['Baz',3]]
What's the best 'Ruby Way' to do this kind of thing?
Thanks!
How about these?
# ['Foo','Bar','Baz']
array = folders.map { |f| f.name }
# This does the same, but only works on Rails or Ruby 1.8.7 and above.
array = folders.map(&:name)
# [['Foo',1],['Bar',2],['Baz',3]]
array = folders.map { |f| [f.name, f.display_order] }
How about:
a.collect {|f| f.name}
You can do
array.map { |a| [a.name, a.display_order] }
To get ['Foo','Bar','Baz'] , you can do: array.map(&:name)
For the second one you could use array.map {|a| [a.id, a.name] }

Resources