Ruby 获取对象键作为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8657740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:37:26  来源:igfitidea点击:

Ruby get object keys as array

ruby

提问by JD Isaacks

I am new to Ruby, if I have an object like this

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

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

How can I return an array of just the keys?

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

["apple", "carrot"]

回答by weezor

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

it's that simple

就这么简单

回答by Tigraine

An alternative way if you need something more (besides using the keysmethod):

如果您需要更多东西(除了使用该keys方法),另一种方法是:

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

obviously you would only do that if you want to manipulate the array while retrieving it..

显然,如果您想在检索数组时操作数组,您只会这样做..

回答by illiptic

Like taro said, keysreturns the array of keys of your Hash:

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

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

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

You'll find all the different methods available for each class.

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

If you don't know what you're dealing with:

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

 puts my_unknown_variable.class.to_s

This will output the class name.

这将输出类名。

回答by ridecar2

Use the keysmethod: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

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