An array is a collection of multiple pieces of information that have the same meaning, and a hash is a collection of multiple pieces of related information.
variable= {Key 1=>Value 1,Key 2=>Value 2,Key 3=>Value 3}
-Since values with different meanings can be combined into one, it is used when managing multiple related values. -Has a set of "data" and the corresponding "name" as an element ・ In hash, data is called value and name is called key.
#If you use a string as the hash key
hash1 = { "name" => "nick", "age" => 30, "country" => "UK" }
・ What is used as a numerical value for the hash key ・ Although it looks like a character string, the actual content is a numerical value. ・ There are two types of writing, but the actual situation is the same for both. ・ Hash3 is the simplest and most often used
#When using a symbol as the hash key
hash2 = { :name => "nick", :age => 30, :country => "UK" }
hash3 = { name: "nick", age: 30, country: "UK" }
⚠️ Computers process numbers faster than strings Symbols are more commonly used
So far, the super basic part is clear! !! It's a good idea to get used to the hashes written with symbols, but make sure you understand them before using them. Next, I would like to explain about adding hashes and getting double hash values! If you want to absorb a little more knowledge, please see the continuation.
teacher = { name: "nick"}
teacher[:age] = 30 #hash[Key to add] =value
puts teacher
#Output result
# {:name=>"nick", :age=>30}
teacher = { name: "nick", age: 30}
teacher[:name] = "john" #hash[The key of the value you want to change] =value
puts teacher
#Output result
# {:name=>"john", :age=>30}
teacher = { name: "nick", age: 30}
puts teacher[:name] #hash[The key of the value you want to get]
#Output result
# nick
#Variable teacher_data → Have multiple pieces of information as hashes inside the array
#teacher_Get name data from data
teacher_data = [
{
teacher: {
profile: {
name: "nick"
}
}
},
{
teacher: {
profile: {
name: "john"
}
}
},
{
teacher: {
profile: {
name: "mac"
}
}
}
]
teacher_data.each do |t|
puts t[:teacher][:profile][:name]
end
#Output result
# nick
# john
# mac
[Explanation] The block argument t uses t of teacher_data. After puts, concatenate the hash [key you want to get] to the data you want to get (name in this case).
Thank you for your hard work! !! That's all for super basic knowledge about hashes and symbols! If you don't understand the basics, you'll be in trouble later, so I hope you take this opportunity to deepen your understanding. Please do not hesitate to let us know if you have any questions or concerns! Then thank you.
・ Htps: // Quiita. This m / Ryosukette r / Te ms / 257d672 Eb83210b5f8dc
Recommended Posts