如何使用Ruby中的变量访问符号哈希键

问题描述 投票:19回答:5

我有一个哈希数组来为其编写通用的检查程序,所以我想传递要检查的键的名称。哈希是用带有符号(冒号前缀)的键定义的。我不知道如何正确使用变量作为键。即使键存在于哈希中,使用变量访问它也将导致nil。

在IRB中,我这样做:

>> family = { 'husband' => "Homer", 'wife' => "Marge" }
=> {"husband"=>"Homer", "wife"=>"Marge"}
>> somevar = "husband"
=> "husband"
>> family[somevar]
=> "Homer"
>> another_family  = { :husband => "Fred", :wife => "Wilma" }
=> {:husband=>"Fred", :wife=>"Wilma"}
>> another_family[somevar]
=> nil
>>

如何通过变量访问哈希键?也许另一种询问方式是,如何将变量强制为符号?

ruby hash
5个回答
32
投票

您首先要将字符串转换为符号:

another_family[somevar.to_sym]

如果您不必担心哈希是符号还是字符串,只需将其转换为符号键即可

请参阅:How do I convert a Ruby hash so that all of its keys are symbols?


3
投票

由于您的键是符号,所以请使用符号作为键。

> hash = { :husband => 'Homer', :wife => 'Marge' }
 => {:husband=>"Homer", :wife=>"Marge"}
> key_variable = :husband
 => :husband
> hash[key_variable]
 => "Homer"

3
投票

您可以使用Active Support gem来访问with_indifferent_access方法:

require 'active_support/core_ext/hash/indifferent_access'
> hash = { somekey: 'somevalue' }.with_indifferent_access
 => {"somekey"=>"somevalue"}
> hash[:somekey]
 => "somevalue"
> hash['somekey']
=> "somevalue"

-1
投票

您在哈希中将其视为变量键的事物称为Symbol,它是Ruby中的结构。它们主要用作哈希键或用于引用方法名称。它们是不可变的,并且在给定时间仅存在任何符号的一个副本,因此可以节省内存。

您可以将带有.to_sym的字符串或符号或带有.to_s的符号转换为字符串,以说明这一点,让我显示此示例:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbolArray = [:HTML, :CSS, :JavaScript, :Python, :Ruby]
# Add your code below!

symbols = Array.new
strings.each {|x|
 symbols.push(x.to_sym)
}

string = Array.new
symbolArray .each {|x|
 string.push(x.to_s)
}
print symbols
print string

结果将是:

[:HTML, :CSS, :JavaScript, :Python, :Ruby]
["HTML", "CSS", "JavaScript", "Python", "Ruby"]

在ruby 9.1中,您会看到在右边带有冒号(:)的符号:

movies = { peter_pan: "magic dust", need_4_speed: "hey bro", back_to_the_future: "hey Doc!" }

我只是想把这一点讲得更讲究一些,所以谁来读这本书都可以用。

最后一件事,这是解决问题的另一种方法:

movie_ratings = {
  :memento =>  3,
  :primer => 3.5,
  :the_matrix => 3,

}
# Add your code below!

movie_ratings.each_key {|k| 
puts k.to_s
}

结果:

memento
primer
the_matrix

-1
投票

如果您将Rails与ActiveSupport一起使用,那么请使用HashWithIndifferentAccess

© www.soinside.com 2019 - 2024. All rights reserved.