Ruby获取对象键作为数组

115

我是 Ruby 的新手,如果我有这样一个对象:

{"apple" => "fruit", "carrot" => "vegetable"}

如何返回一个只包含键的数组?

["apple", "carrot"]

你的对象是一个哈希,因此你可以像 {"apple" => "fruit", "carrot" => "vegetable"}.keys 一样使用 keys 方法。欲了解更多信息,请访问 http://ruby-doc.org/core-1.9.3/。 - taro
4个回答

245
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys   #=> ["apple", "carrot"]

就是这么简单


20

如果您需要除了使用keys方法之外的更多内容,可以采用替代方法:

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

显然,只有在想要在检索数组时操纵数组时才会这样做。


6

像taro所说的那样,keys会返回你的哈希表中所有键的数组:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

你可以在文档中找到每个类可用的不同方法。

如果你不知道自己在处理什么:

 puts my_unknown_variable.class.to_s

这将输出类名。


3
使用keys方法:{"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接