Created
January 21, 2019 20:00
-
-
Save parzibyte/963b9d55391ba9a68c4305e726d26747 to your computer and use it in GitHub Desktop.
Escribir a archivo CSV created by parzibyte - https://repl.it/@parzibyte/Escribir-a-archivo-CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Escribir contenido CSV a un archivo con Ruby | |
@author parzibyte | |
=end | |
require 'csv' #La clase que nos ayuda | |
NOMBRE_ARCHIVO = "productos.csv" | |
# Una simple clase para encapsular todo | |
class Producto | |
attr_reader :descripcion, :precio_compra, :precio_venta, :cantidad | |
def initialize(descripcion, precio_compra, precio_venta, cantidad) | |
@descripcion = descripcion | |
@precio_compra = precio_compra | |
@precio_venta = precio_venta | |
@cantidad = cantidad | |
end | |
end | |
# Un arreglo de productos que vamos a escribir en el CSV | |
productos = [ | |
Producto.new("Galletas", 10, 15, 100), | |
Producto.new("Papas fritas", 15, 17, 10), | |
Producto.new("Chocolate", 3, 5, 50), | |
Producto.new("Jugo de manzana", 9, 11, 200), | |
] | |
CSV.open(NOMBRE_ARCHIVO, "a") do |archivo| # Abrir archivo en modo [a]ppend | |
productos.each do |p| | |
# Le pasamos un arreglo. Cada valor es una columna | |
archivo << [p.descripcion, p.precio_compra, p.precio_venta, p.cantidad] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Galletas | 10 | 15 | 100 | |
---|---|---|---|---|
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 | |
Galletas | 10 | 15 | 100 | |
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 | |
Galletas | 10 | 15 | 100 | |
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 | |
Galletas | 10 | 15 | 100 | |
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 | |
Galletas | 10 | 15 | 100 | |
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 | |
Galletas | 10 | 15 | 100 | |
Papas fritas | 15 | 17 | 10 | |
Chocolate | 3 | 5 | 50 | |
Jugo de manzana | 9 | 11 | 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment