Ruby CSV - JSON - YMAL
Objetives

CSV
Comma-Separated Values

# Syntaxes
# favorite_foods.csv
id,name
1,chocolate
2,bacon
3,apple
4,banana
# ========== #
csv_format = "id,name\n1,chocolate\n2,bacon\n3,apple\n4,banana\n"
# Read
require 'csv'
csv_read = CSV.read("favorite_foods.csv")
p csv_read
# Parse
require 'csv'
csv_parse = CSV.parse("id,name\n1,chocolate\n2,bacon\n3,apple\n4,banana\n5,almonds")
p csv_parse
# Result
[
["id", "name"],
["1", "chocolate"],
["2", "bacon"],
["3", "apple"],
["4", "banana"],
["5", "almonds"]
]
CSV Methods

# CSV read
require 'csv'
table = CSV.read("favorite_foods.csv", headers: true)
# table = CSV.parse(File.read("favorite_foods.csv"), headers: true)
# CSV read
require 'csv'
table = CSV.read('favorite_foods.csv', headers: true)
# table['file']['column']
table[0]["id"]
# "1"
table[0]["name"]
# "chocolate"
# by_col
table.by_col[0]
# ["1", "2", "3", "4", "5"]
table.by_col[1]
# ["chocolate", "bacon", "apple", "banana", "almonds"]
# by_row
table.by_row[0]
#<CSV::Row "id":"1" "name":"chocolate">
table.by_row[1]
#<CSV::Row "id":"2" "name":"bacon">
# Exercise
table.each do |row_object|
p "[#{row_object['id']}, #{row_object['name']}]"
p "-"*10
end
How to create a CSV

# Create a CSV string
cats = [
[:blue, 1],
[:white, 2],
[:black_and_white, 3]
]
csv_cats = cats.map { |c| c.join(",") }.join("\n")
p csv_cats
# With 'generate'
require 'csv'
csv_cats = CSV.generate do |csv|
csv << [:blue, 1]
csv << [:white, 2]
csv << [:black_and_white, 3]
end
p csv_cats
New CSV File

# Create CSV File
CSV.open("cats.csv", "w") do |csv|
csv << [:blue, 1]
csv << [:white, 2]
csv << [:black_and_white, 3]
end
# Append
CSV.open("cats.csv", "a") do |csv|
csv << [:brown, 4]
end
JSON
JavaScript Object Notation

# Syntaxes
json = {
"key": "value"
}
JSON Methods

require 'json'
pokemon = {
name: "Bulbasaur",
type: ["grass", "poison"],
weaknesses: ["Fire","Psychic","Flying","Ice"]
}
pokemon.methods
# From Hash to JSON
puts json_string = pokemon.to_json # built-in method
puts json_string = JSON.generate(pokemon) # generates a json string
p json_string = JSON.dump(pokemon) # generate with presets and a limit
# From JSON to Hash
p json_hash = JSON.parse json_string # a string
puts json_hash = JSON.load json_string # a IO stream => File
Read / Write

# Read
require 'json'
file = File.read('books.json')
data_hash = JSON.parse(file)
data_hash['books']['1'] = 'I, Robot'
data_hash['books']['2'] = 'The Caves of Steel'
# Write
File.open("saved_hash.json","w") do |file|
file.write data_hash.to_json
end
YAML
Yet Another Markup Language

# Syntaxes
---
:name: Bulbasaur
:type:
- grass
- poison
:weaknesses:
- Fire
- Psychic
- Flying
- Ice
# Other form.
---
:name: Bulbasaur
:type: ['grass', 'poison']
:weaknesses: ['Fire', 'Psychic', 'Flying', 'Ice']
YAML Methods

require 'yaml'
pokemon = {
name: "Bulbasaur",
type: ["grass", "poison"],
weaknesses: ["Fire","Psychic","Flying","Ice"]
}
# Hash to YAML
yaml_string = pokemon.to_yaml # built-in method
yaml_string_dump = YAML.dump(pokemon)
# YAML to Hash
yaml_object = YAML.load(yaml_string)
Write / Read

# Write
require 'yaml'
pokemon = {
name: "Bulbasaur",
type: ["grass", "poison"],
weaknesses: ["Fire","Psychic","Flying","Ice"]
}
# Write (or overwrite) our character to `saved_hash.txt`
File.open("saved_hash.yaml","w") do |file|
file.write pokemon.to_yaml
end

# Read
# Read file & parsed to hash
parsed = YAML.load(File.read("saved_hash.yaml"))
p parsed
Ruby CSV / JSON / YAML
By Paulo Tijero
Ruby CSV / JSON / YAML
- 121