📜  红宝石 |哈希基础

📅  最后修改于: 2022-05-13 01:54:33.375000             🧑  作者: Mango

红宝石 |哈希基础

哈希是一种数据结构,它维护一组称为键的对象,每个键都将一个值与其相关联。简单来说,散列是唯一键及其值的集合。哈希有时被称为关联数组,因为它将值与每个键相关联,但哈希和数组之间存在差异。数组始终使用整数值进行索引,而哈希使用对象。哈希也称为映射,因为它们将键映射到值。

散列字面量或创建散列:散列是使用散列文字创建的,散列字面量是一个以逗号分隔的键/值对列表,并且始终包含在花括号 {} 中。有多种创建哈希的方法:

  • 使用新的类方法:的类方法将创建一个空散列,这意味着创建的散列将没有默认值。

    句法:

    hash_variable = Hash.new

    例子:

    geeks = Hash.new

    这将创建一个空的哈希geeks 。您还可以通过以下两种方式向极客提供默认值:

    geeks = Hash.new("GFG")
    
    or
    
    geeks = Hash.new "GFG"
    

    这里GFG是默认值。每当上面的散列中不存在键或值时,访问散列将返回默认值“GFG”。要提供键/值对,您必须修改本文下面讨论的哈希值。

  • 使用 {} 大括号:在这个散列变量后面是=花括号 {} 。在大括号 {} 之间,创建了键/值对。

    句法:

    hash_variable = {"key1" => value1, "key2" => value2}
    

获取哈希值:要获取哈希值,请始终将所需的键放在方括号 []中。

例子:

# Ruby program to demonstrate the creation
# of hashes and fetching the hash values
  
#!/usr/bin/ruby
  
# Creating a hash using new class method
# without the default value
geeks = Hash.new
  
# empty hash will return nothing on display
puts "#{geeks[4]}"
  
# creating hash using new class method
# providing default value
# this could be written as 
# geeks = Hash.new "GFG"
geeks_default = Hash.new("GFG")
  
# it will return GFG for every index of hash
puts "#{geeks_default[0]}"
puts "#{geeks_default[7]}"
  
# creating hash using {} braces
geeks_hash1 = {"DS" => 1, "Java" => 2}
  
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  

输出:

GFG
GFG
1
2

在 Ruby 中修改散列:可以通过在已经存在的散列中添加或删除键值/对来修改散列。此外,您可以更改散列中键的现有值。

例子:

# Ruby program to demonstrate the modifying of hash
  
#!/usr/bin/ruby
  
# creating hash using {} braces
geeks_hash1 = {"DS" => 1, "Java" => 2}
  
puts "Before Modifying"
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  
  
puts "\n"
  
puts "After Modifying"
  
# modifying hash values
geeks_hash1["DS"] = 4
geeks_hash1["Java"] = 5
  
# fetching values of hash using []
puts geeks_hash1['DS'] 
puts geeks_hash1['Java'] 

输出:

Before Modifying
1
2

After Modifying
4
5

注意:每当用户为哈希中的同一个键提供两个不同的值时,键的先前值将被键的最新值覆盖。此外,程序将成功运行,但会发出警告,如下例所示:

# Ruby program to demonstrate the modifying hash
  
#!/usr/bin/ruby
  
# creating hash using {} braces
# providing two different values to key "DS"
geeks_hash1 = {"DS" => 1, "DS" => 4,"Java" => 2}
  
puts "Before Modifying"
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  
  
puts "\n"
  
puts "After Modifying"
  
# modifying hash values
geeks_hash1["DS"] = 4
geeks_hash1["Java"] = 5
  
# fetching values of hash using []
puts geeks_hash1['DS'] 
puts geeks_hash1['Java'] 

输出:

Before Modifying
4
2

After Modifying
4
5
main.rb:7: warning: key "DS" is duplicated and overwritten on line 7