{} 或 Hash.new 方法创建一个空的哈希表。例如:hash1 = {} # 创建一个空哈希表 hash2 = Hash.new # 创建一个空哈希表,并提供一个默认值 [] 操作符或 []= 操作符向哈希表中添加键值对。例如:hash1["name"] = "Alice" # 添加一个键值对,键为 "name",值为 "Alice" hash2["age"] = 30 # 添加一个键值对,键为 "age",值为 30 name = hash1["name"] # 返回 "Alice" age = hash2["age"] # 返回 30 has_key? 方法检查哈希表中是否存在某个键。例如:hash1.has_key?("name") # 返回 true hash1.has_key?("address") # 返回 false delete 方法删除哈希表中的某个键值对。例如:hash1.delete("name") # 删除键为 "name" 的键值对,返回被删除的值(即 "Alice") each 方法遍历哈希表中的所有键值对。例如:hash1.each do |key, value| puts "#{key}: #{value}" end 这将输出:
name: Alice merge 方法合并两个哈希表。例如:hash1 = {"name" => "Alice", "age" => 30} hash2 = {"age" => 31, "city" => "New York"} merged_hash = hash1.merge(hash2) # 合并 hash2 到 hash1,返回新的哈希表 这将返回:
{"name" => "Alice", "age" => 31, "city" => "New York"} 注意:在合并哈希表时,如果两个哈希表中有相同的键,那么后一个哈希表中的值将覆盖前一个哈希表中的值。