我是 Ruby 的新手,如果我有这样一个对象:
{"apple" => "fruit", "carrot" => "vegetable"}
如何返回一个只包含键的数组?
["apple", "carrot"]
我是 Ruby 的新手,如果我有这样一个对象:
{"apple" => "fruit", "carrot" => "vegetable"}
如何返回一个只包含键的数组?
["apple", "carrot"]
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys #=> ["apple", "carrot"]
就是这么简单
如果您需要除了使用keys
方法之外的更多内容,可以采用替代方法:
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }
显然,只有在想要在检索数组时操纵数组时才会这样做。
像taro所说的那样,keys
会返回你的哈希表中所有键的数组:
http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys
你可以在文档中找到每个类可用的不同方法。
如果你不知道自己在处理什么:
puts my_unknown_variable.class.to_s
这将输出类名。
keys
方法:{"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]
{"apple" => "fruit", "carrot" => "vegetable"}.keys
一样使用keys
方法。欲了解更多信息,请访问 http://ruby-doc.org/core-1.9.3/。 - taro