📜  ruby hash除了嵌套 (1)

📅  最后修改于: 2023-12-03 15:34:45.401000             🧑  作者: Mango

Ruby Hash除了嵌套

Hash 在 Ruby 中是一种重要的数据结构,它可以方便地访问和管理大量数据。除了常见的键值对,Ruby Hash 还有许多强大的特性,今天我们来一起探索一下。

Ruby Hash 的创建与操作
创建 Hash
# 使用字面量创建 Hash
hash = { "key1" => "value1", "key2" => "value2" }

# 使用 Hash.new 创建 Hash
hash = Hash.new
hash["key1"] = "value1"
hash["key2"] = "value2"
访问 Hash 中的元素
hash = { "key1" => "value1", "key2" => "value2" }
hash["key1"] # => "value1"

# 判断 Hash 中是否包含某个键
hash.has_key?("key1") # => true
更新 Hash
# 直接赋值更新
hash["key1"] = "new_value1"

# 使用 merge 方法合并 Hash
hash1 = { "key1" => "value1", "key2" => "value2" }
hash2 = { "key1" => "new_value1", "key3" => "value3" }
hash = hash1.merge(hash2) # => { "key1" => "new_value1", "key2" => "value2", "key3" => "value3" }
Ruby Hash 的迭代与遍历
迭代 Hash
hash = { "key1" => "value1", "key2" => "value2" }
hash.each do |key, value|
  puts "#{key}: #{value}"
end
# 输出
# key1: value1
# key2: value2
遍历 Hash
hash = { "key1" => "value1", "key2" => "value2" }
hash.keys.each do |key|
  puts key
end
# 输出
# key1
# key2

hash.values.each do |value|
  puts value
end
# 输出
# value1
# value2
Ruby Hash 的排序与过滤
排序 Hash
# 按键排序
hash = { "b" => "value1", "a" => "value2", "c" => "value3" }
hash.sort_by {|key, value| key}.to_h
# => {"a"=>"value2", "b"=>"value1", "c"=>"value3"}

# 按值排序
hash.sort_by {|key, value| value}.to_h
# => {"b"=>"value1", "a"=>"value2", "c"=>"value3"}
过滤 Hash
# 选择键值符合条件的元素
hash = { "key1" => 1, "key2" => 2, "key3" => 3 }
hash.select {|key, value| value > 1} # => {"key2" => 2, "key3" => 3}

# 排除键值符合条件的元素
hash.reject {|key, value| value > 1} # => {"key1" => 1}

以上就是 Ruby Hash 的基本操作,接下来我们来看一些 Hash 的高级用法。

Ruby Hash 的高级用法
Hash 的默认值
# 在创建 Hash 时设置默认值
hash = Hash.new(0)
hash["key1"] += 1
hash["key2"] # => 0

# 在创建 Hash 时指定默认值块
hash = Hash.new {|hash, key| hash[key] = 0}
一键多值
# 用数组存储一键多值
hash = {}
hash["key1"] = ["value1", "value2"]
hash["key2"] = ["value3"]
hash["key1"].each {|value| puts value}
# 输出
# value1
# value2
嵌套 Hash

Hash 可以嵌套使用,非常适合用来表示多层次结构的数据。

# 嵌套 Hash
hash = {
  "key1" => {
    "subkey1" => "value1",
    "subkey2" => "value2"
  },
  "key2" => {
    "subkey3" => "value3"
  }
}
hash["key1"]["subkey1"] #=> "value1"
Hash 的序列化
require 'json'

hash = { "key1" => "value1", "key2" => "value2" }
json = JSON.generate(hash) # => "{\"key1\":\"value1\",\"key2\":\"value2\"}"
hash = JSON.parse(json) # => {"key1"=>"value1", "key2"=>"value2"}

以上就是 Ruby Hash 的基本用法和高级技巧,希望本篇文章能帮助大家更好地理解 Ruby Hash。