Skip to content

Instantly share code, notes, and snippets.

@directionless
Last active Feb 9, 2017
Embed
What would you like to do?
Ruby CSV Converters What's Wrong
require 'csv'
CSV::Converters[:num2] = lambda do |num|
puts "Converter called with #{num}"
return num unless num.is_a?(Numeric)
sprintf('%.2f', num)
end
CSV.instance($stdout,
{ headers: [:name, :val] , write_headers: true,
:converters => [:num2]}) do |csv|
csv << { name: "a", val: 1 }
csv << { name: "b", val: 0.0 }
csv << { name: "c", val: 6.666666666666 }
end
seph$ ruby --version
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin15]
seph$ ruby /tmp/x.rb
Converter called with name
Converter called with val
name,val
a,1
b,0.0
c,6.666666666666
require 'csv'
csv = CSV.instance($stdout, {
headers: [:name, :val],
write_headers: true,
})
csv.convert do |num|
begin
puts "Converter called with #{num}"
sprintf('%.2f', num)
rescue
num
end
end
csv << { name: "a", val: 1 }
csv << { name: "b", val: 0.0 }
csv << { name: "c", val: 6.666666666666 }
puts csv.converters
puts csv.converters.first.call(6.666666666)
seph$ ruby --version
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin15]
seph$ ruby /tmp/x.rb
Converter called with name
Converter called with val
name,val
a,1
b,0.0
c,6.666666666666
#<Proc:0x007fb55a93b158@/tmp/x.rb:8>
Converter called with 6.666666666
6.67
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment