Back-end
[루비] Hash
jhkang-dev
2018. 12. 22. 00:21
sample_hash={'a'=> 1, 'b'=>2, 'c'=>3}
my_details={:name=>'mashrur', :favcolor=>'red'}
my_details['favcolor']
sample_hash['a']
my_hash={a:2}
another_hash={a:1, b:2, c:3}
another_hash[:a]
#Hash의 키만 가져온다.
sample_hash.keys
sample_hash.each do |key, value|
puts "The class for key is #{key.class} and the value is #{value.class}"
end
sample_hash.each do |key, value|
puts "The class for key is #{key.class} and the value is #{value.class}"
end
#키, 밸류 추가
my_hash[:e] = "Mashrur"
my_hash
my_hash[:c]="cat"
my_hash.each {|some_key, some_value| puts "The key is #{some_key} adn the valuse is #{some_value}"}
# 밸류가 String 타입인 키와 밸류를 출력한다.
my_hash.select {|k, v| v.is_a?(String)}
my_hash.each { |k,v| my_hash.delete(k) if v.is_a?(String)}
#hash_first 이름의 해쉬를 생성한다.
hash_first={'name'=> 'mashrur', 'favcolor'=>'red'}
#'favcolor' 키의 value 값을 리턴 받는다.
hash_first["favcolor"]
#해쉬를 다음과 같이 생성한다. 키를 적고 콜론 뒤에 값을 적는다.
hash_second={a:1, b:2, c:3, d:4}
#해쉬의 키에 대한 값을 불러올 때 다음과 같이도 할 수 있다.
hash_second[:c]
#해쉬에 key d를 가진 밸류를 변경
hash_second[:d]=7
hash_second.delete(:d)
hash_second.each {|somekey, somevalue| puts somevalue}
hash_second.each {|somekey, somevalue| puts "The key is #{somekey} and the value is #{somevalue}"}
hash_second.each {|somekey, somevalue| puts "The key is #{somekey} and the value is #{somevalue}"}
# 3보다 큰 value를 가진 키를 삭제하라는 것을 each문을 돌려서 함.
hash_second.each {|k, v| hash_second.delete(k) if v > 3}
hash_second.select {|k,v| v.odd?}