Intern
What is a hash (HASH) in Ruby?
sobes.tech AI
Answer from AI
Hash in Ruby is an ordered collection of key-value pairs, where each unique key is associated with a specific value. Keys are usually symbols (Symbol) or strings (String), but can be any objects that implement the eql? and hash methods.
Features of hash:
- Orderliness: Since Ruby 1.9, hashes maintain the insertion order of elements.
- Access by key: Values are accessed quickly via the corresponding key.
- Dynamic size: Hashes can expand or contract as elements are added or removed.
- No duplicate keys: Each key is unique within a hash.
Examples of creating a hash:
# Using a literal
person = { "name" => "Alice", "age" => 30 }
# Using symbols as keys (more common and efficient way)
settings = { :theme => "dark", :language => "ru" }
# Key-Value Pair Shorthand notation, with Ruby 1.9
config = { host: "localhost", port: 8080 }
# Using Hash.new constructor
empty_hash = Hash.new
Main operations with hashes:
| Operation | Example | Description |
|---|---|---|
| Access value | person["name"] |
Returns the value for the key "name" |
| Add/modify | person["city"] = "New York" |
Adds a pair or modifies the value for the key |
| Delete | person.delete("age") |
Removes the pair with the key "age" |
| Size | person.size or person.length |
Returns the number of pairs in the hash |
| Check key | person.key?("name") |
Checks if the key exists in the hash |
| Check value | person.value?(30) |
Checks if the value exists in the hash |
| Iteration | `person.each { | key, value |
| Return keys | person.keys |
Returns an array of all keys |
| Return values | person.values |
Returns an array of all values |
Usage example:
user_data = {
name: "Boris",
age: 45,
city: "Moscow"
}
# Accessing data
puts user_data[:name] # => Boris
# Adding a new field
user_data[:job] = "Developer"
# Changing a value
user_data[:age] = 46
# Removing a field
user_data.delete(:city)
# Iterating over the hash
user_data.each do |key, value|
puts "#{key}: #{value}"
end