Ruby Basics - Hashes
# Creating a hash
old_syntax_hash = {:name => 'john'}
p old_syntax_hash
new_syntax_hash = { name: 'john'}
p new_syntax_hash
# Output>
# {:name=>"john"}
# {:name=>"john"}
# Example
hsh = colors = {
"red" => 0xf00,
"green" => 0x0f0,
"blue" => 0x00f,
}
# Add new item
hsh[:white] = 0xfff
# Remove an item
hsh.delete(:green)
p hsh[:white] # > 4095
# Iterating over hashes
hsh.each do |key, value|
print key, " is ", value, "\n"
end
# Output :
# red is 3840
# green is 240
# ...
# Merge two hashes
hsh2 ={
"gold" => 0xffd
}
hsh.merge!(hsh2)
p hsh
# {"red"=>3840, "green"=>240, "blue"=>15, :white=>4095, "gold"=>4093}