📜  Ruby哈希

📅  最后修改于: 2021-01-08 13:12:33             🧑  作者: Mango

红宝石哈希

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 Hash

可以通过在现有哈希中添加或删除键值对来修改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哈希有很多方法。一些是公共类方法,一些是公共实例方法。

公开课方法

Method Description
Hash[object] Create a new hash with given objects.
new(obj) Return a new empty hash.
try_convert(obj) Try to convert obj into hash.

公共实例方法

Method Description
hsh==other_hash Two hashes are equal if they contain same key and value pair.
hsh[key] Retrieve value from the respective key.
hsh[key] = value Associates new value to the given key.
assoc(obj) Compare obj in the hash.
clear Remove all key value pair from hash.
compare_by_identity Compare hash keys by their identity.
compare_by_identity? Return true if hash compare its keys by their identity.
default(key=nil) Return default value.
default = obj Sets the default value.
delete(key) Delete key value pair.
each Call block once for each key in hash.
empty? Return true if hash contains no key value pair.
eql>(other) Return true if hash and other both have same content
fetch(key[, default]) Return value from hash for a given key.
flatten Return a new array that is a one-dimensional flattening of this hash.
has_key?(key) Return true if given key is present in hash.
has_value?(value) Return true if given value is present in hash for a key.
include?(key) Return true if given key is present in hash.
to_s/ inspect Return content of hash as string.