Programing

Ruby는 객체 키를 배열로 가져옵니다.

lottogame 2020. 9. 4. 08:04
반응형

Ruby는 객체 키를 배열로 가져옵니다.


저는 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"]

참고 URL : https://stackoverflow.com/questions/8657740/ruby-get-object-keys-as-array

반응형