Ruby将对象键作为数组获取

JD *_*cks 92 ruby

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

{"apple" => "fruit", "carrot" => "vegetable"}
Run Code Online (Sandbox Code Playgroud)

我怎样才能返回一个只有键的数组?

["apple", "carrot"]
Run Code Online (Sandbox Code Playgroud)

小智 206

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys   #=> ["apple", "carrot"]
Run Code Online (Sandbox Code Playgroud)

就这么简单

  • +1谢谢,(不能接受你的回答,直到时间限制) (2认同)

Tig*_*ine 15

如果你需要更多东西(除了使用keys方法)之外的另一种方法:

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }
Run Code Online (Sandbox Code Playgroud)

很明显,如果你想在检索它时操纵数组,你只会这样做.


ill*_*tic 6

就像芋头说的,keys返回哈希的键数组:

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

您将找到每个类可用的所有不同方法。

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

 puts my_unknown_variable.class.to_s
Run Code Online (Sandbox Code Playgroud)

这将输出类名。