Hashes in Ruby

Hashes are data structures that allow key-value pairs to be stored. They are a fundamental tool in Ruby to work with data in an organized and efficient way.

Creating and accessing values: Link to heading

  • They can be created using curly braces and separating pairs with commas.
  • The size of the hash can be obtained with the size method.
  • Values ​​can be accessed by their key.

Examples: Link to heading

capitals = { }

capitals.class # => Hash

capitals = { "Spain" => "Madrid" }

# Add value
capitals["Uruguay"] = "Montevideo"

puts capitals # => { "Spain" => "Madrid", "Uruguay" => "Montevideo" }

# Access a specific value
capitals["Spain"] # => "Madrid"

capitals.size # => 2

capitals.empty? # => false

capitals.has_value? "Spain" # => false

capitals.has_key? "Spain" # => true

# Invert the hash (convert values ​​to keys)
capitals.invert # => { "Madrid" => "Spain", "Montevideo" => "Uruguay" }

# Mix two hashes
capitals.merge({"Brazil" => "Brasilia"}) # => {"Spain" => "Madrid", "Uruguay" => "Montevideo", "Brazil" => "Brasilia"}

# Transform the values
capitals.transform_values ​​{ |x| x.downcase } # => {"spain" => "madrid", "uruguay" => "montevideo"}

# Print the content of the hash
puts capitals.map { |k, v| "The capital of #{k} is #{v}" } # The capital of Spain is Madrid, The capital of Uruguay is Montevideo

# Convert an array to a hash
[["hello", 13], ["world", 14]].to_h # => {"hello" => 13, "world" => 14}

Useful methods: Link to heading

  • each: Loops through the hash and executes a block of code for each key-value pair.
  • select: Filters the hash key-value pairs and returns a new hash with those that meet a condition.
  • keys: Obtains an array with the hash keys.
  • values: Obtains an array with the hash values.

Example: Link to heading

capitals.each { |k, v| puts "The capital of #{k} is #{v}" } # The capital of Spain is Madrid, The capital of Uruguay is Montevideo

capitals.select { |k, v| v.length > 8 } # => {"Uruguay" => "Montevideo"}

capitals.keys # => ["Spain", "Uruguay"]

capitals.values ​​# => ["Madrid", "Montevideo"]

Hashes are a powerful tool for storing and organizing data in Ruby. Their flexibility and efficiency make them a fundamental part of the language.

Keep learning about hashes to take full advantage of Ruby!

<< Arrays in Ruby Conditionals in Ruby >>