[Ruby] How do I use built-in data structures like dictionaries or maps in Ruby?

In Ruby, dictionaries or maps are represented by a data structure called Hash. Here's how you can use Hashes in Ruby:

Creating a Hash: You can create a Hash by using the curly braces {} or the Hash.new method.

1hash1 = { "name" => "John", "age" => 30 }
2hash2 = Hash.new

Accessing Values: To access a value in a Hash, you can use square brackets [] and provide the corresponding key.

1hash1["name"] # returns "John"

Adding or Modifying Values: To add or modify values in a Hash, you can use the square brackets [] along with the assignment operator =.

1hash1["email"] = "john@example.com" # adds a new key-value pair
2hash1["name"] = "John Doe" # updates the value of an existing key

Deleting Values: To delete a value in a Hash, you can use the delete method and provide the corresponding key.

1hash1.delete("age") # deletes the key-value pair with the given key

Iterating Over a Hash: You can iterate over a Hash using various methods like each, each_key, each_value, or each_pair.

1hash1.each do |key, value|
2  puts "#{key}: #{value}"
3end

Checking if a Key Exists: To check if a key exists in a Hash, you can use the has_key? method or the key? method.

1hash1.has_key?("name") # returns true if the key exists, false otherwise

These are some basic operations you can perform on Hashes in Ruby. There are many more methods and functionalities available for working with Hashes in Ruby, so you can explore the Ruby documentation for more details.