Ruby获取对象键作为数组


97

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

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

如何返回仅包含键的数组?

["apple", "carrot"]

你的目标是一个Hash,所以你可以使用keys类似的方法{"apple" => "fruit", "carrot" => "vegetable"}.keys。欲了解更多信息,请访问ruby-doc.org/core-1.9.3
芋头

Answers:


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

就这么简单


16

如果您还需要其他keys方法(使用方法),可以使用以下替代方法:

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

显然,只有在检索数组时要操作数组时,您才这样做。



2

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.