Rubyは配列としてオブジェクトキーを取得します


97

このようなオブジェクトがあれば、Rubyは初めてです。

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

キーだけの配列を返すにはどうすればよいですか?

["apple", "carrot"]

オブジェクトはハッシュなので、のようkeysなメソッドを使用できます{"apple" => "fruit", "carrot" => "vegetable"}.keys。詳細については、ruby-doc.org / core
taro

回答:


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

とても簡単です


16

keysメソッドを使用する以外に)さらに何かが必要な場合の代替方法:

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

明らかにそれを取得しながら配列を操作したい場合にのみそれを行います。


4

taroが言ったようkeysに、ハッシュのキーの配列を返します。

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

各クラスで使用できるさまざまなメソッドがすべて見つかります。

何を扱っているのかわからない場合:

 puts my_unknown_variable.class.to_s

クラス名が出力されます。


2

次のkeys方法を使用します。{"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.