Ruby 哈希
Ruby 哈希
Ruby 哈希是唯一键及其值的集合。它们类似于数组,但数组使用整数作为索引,散列使用任何对象类型。它们也称为关联数组、字典或映射。
如果使用不存在的键访问哈希,则该方法将返回 nil。
语法:
name = {
"key1" =>
"value1",
"key2" =>
"value2",
"key3" =>
"value3"...} OR name = {key1:
'value1', key2:
'value2', key3:
'value3'...}
创建 Ruby 哈希
Ruby 哈希是通过在 {} 大括号内写入键值对来创建的。
要获取哈希值,请在 [] 方括号内写入所需的键。
示例:
color = {
"Rose" =>
"red",
"Lily" =>
"purple",
"Marigold" =>
"yellow",
"Jasmine" =>
"white" } puts color[
'Rose'] puts color[
'Lily'] puts color[
'Marigold'] puts color[
'Jasmine']
输出:
修改 Ruby 哈希
可以通过在现有哈希中添加或删除键值对来修改 Ruby 哈希。
示例:
color = {
"Rose" =>
"red",
"Lily" =>
"purple",
"Marigold" =>
"yellow",
"Jasmine" =>
"white" } color[
'Tulip'] =
"pink" color.each
do
|key, value| puts
"#{key} color is #{value}" end
输出:
Ruby 哈希方法
Ruby 哈希有很多方法。一些是公共类方法和一些公共实例方法。
公共类方法
方法 |
说明 |
Hash[object] |
用给定的对象创建一个新的哈希。 |
new(obj) |
返回一个新的空散列。 |
try_convert(obj) |
尝试将 obj 转换为哈希。 |
公共实例方法
方法 |
说明 |
hsh==other_hash |
如果两个哈希值包含相同的键值对,则它们相等。 |
hsh[key] |
从相应的键中检索值。 |
hsh[key] = vlaue |
将新值与给定的键相关联。 |
assoc(obj) |
比较哈希中的obj。 |
clear |
从哈希中删除所有键值对。 |
compare_by_identity |
通过身份比较哈希键。 |
compare_by_identity? |
如果 hash 通过它们的身份比较它的键,则返回 true。 |
default(key=nil) |
返回默认值。 |
default = obj
|
设置默认值。 |
delete(key) |
删除键值对。 |
each |
对哈希中的每个键调用一次块。 |
empty? |
如果 hash 不包含键值对,则返回 true。 |
eql>(other) |
如果 hash 和 other 的内容相同则返回 true |
fetch(key[, default])
|
从给定键的哈希返回值。 |
flatten |
返回一个新数组,该数组是此哈希的一维扁平化。 |
has_key?(key) |
如果给定的键存在于哈希中,则返回 true。 |
has_value?(value) |
如果给定值存在于键的哈希中,则返回 true。 |
include?(key) |
如果给定的键存在于哈希中,则返回 true。 |
to_s/inspect
|
将哈希的内容作为字符串返回。 |