Edited at

yaml: 配列と hash の cheat sheet

More than 3 years have passed since last update.

code


cheet_sheet.rb

require 'yaml'

array_of_string = ['a', 'b', 'c']
array_of_array = [
['a1', 'a2'],
['b1', 'b2'],
['c1', 'c2'],
]
array_of_hash = [
{'k1' => 'v1'},
{'k2' => 'v2'},
{'k3' => 'v3'},
]
hash_of_string_to_string = {
'k1' => 'v1',
'k2' => 'v2',
'k3' => 'v3',
}
hash_of_string_to_array = {
'k1' => [ 'a1', 'a2' ],
'k2' => [ 'b1', 'b2' ],
'k3' => [ 'c1', 'c2' ],
}
hash_of_string_to_hash = {
'k1' => {
'K11' => 'V11',
'K12' => 'V12'
},
'k2' => {
'K21' => 'V21',
'K22' => 'V22',
},
'k3' => {
'K31' => 'V31',
'K32' => 'V32',
},
}
puts 'array_of_string'
puts YAML.dump(array_of_string)
puts
puts 'array_of_array'
puts YAML.dump(array_of_array)
puts
puts 'array_of_hash'
puts YAML.dump(array_of_hash)
puts
puts 'hash_of_string_to_string'
puts YAML.dump(hash_of_string_to_string)
puts
puts 'hash_of_string_to_array'
puts YAML.dump(hash_of_string_to_array)
puts
puts 'hash_of_string_to_hash'
puts YAML.dump(hash_of_string_to_hash)


実行結果

array_of_string

---
- a
- b
- c

array_of_array
---
- - a1
- a2
- - b1
- b2
- - c1
- c2

array_of_hash
---
- k1: v1
- k2: v2
- k3: v3

hash_of_string_to_string
---
k1: v1
k2: v2
k3: v3

hash_of_string_to_array
---
k1:
- a1
- a2
k2:
- b1
- b2
k3:
- c1
- c2

hash_of_string_to_hash
---
k1:
K11: V11
K12: V12
k2:
K21: V21
K22: V22
k3:
K31: V31
K32: V32