Hash에서 값을 얻는 방법(feat. try, fetch, dig) (How to use try, fetch and dig for getting value from hash)



### Hash에서 값을 얻는 방법

데이터를 다루다 보면 자주 Hash (다른 언어에선 Dictionary 라고도 하는)를 사용하게 되는데, Hash에서 데이터를 얻을 때, 어떻게 뽑아내는지와 주의해야할 점에 대해 적으려고 한다. 예제를 통해 알아보자.

---

#### fetch

일단 간단한 Hash를 하나 만들어본다.

```ruby
hash = {:apple=>{:color=>"red"}, :banana=>"yellow", :melon=>"gree
"}
# => {:apple=>{:color=>"red"}, :banana=>"yellow", :melon=>"green"}
```

그 다음 [] 으로 값을 얻어보자. banana 키의 yellow 라는 값을 얻고 싶다면,

```ruby
hash[:banana] 
#=> "yellow"
```

아주 간단하다. 하지만 banana이라는 key가 없거나 오타가 있다면 어떻게 될까?

```ruby
hash[:banaan].upcase
# NoMethodError (undefined method `upcase' for nil:NilClass)
```

위와 같이 에러가 뜬다. 이런 상황을 방지하기 위해 `fetch`를 사용한다.

```ruby
hash.fetch(:banaan, "yellow").upcase
# => "YELLOW"
```

---

#### try

이번엔 red의 값을 찾아보자.

```ruby
hash[:apple][:color]
# => "red"
```

하지만 만약 apple 의 값이 nil 이거나 apple이 아니라 오타가 난다면 ? 아래와 같이 에러가 난다.

```ruby
hash[:appl][:color]
# => NoMethodError (undefined method `[]' for nil:NilClass)
```

이를 방지하기 위해 try를 사용할 수 있다. 아래와 같이 사용하면 nil을 return 한다.

```ruby
hash.try(:[], :appl).try(:[], :color)
# => nil
```

만약 depth 가 길어진다면 계속 try try ... 하게 될텐데 이 때 사용하는 함수가 dig 다(~~디그다디그다닥트닥트닥트~~)

---

#### dig

```ruby
hash.dig(:apple, :color)
# => "red"

hash.dig(:appl, :color)
# => nil
```



이렇게 Hash 에서 값을 얻는 방법을 알아봤다.


댓글

이 블로그의 인기 게시물

부트스트랩 사용 시 버튼 오른쪽 정렬하는 방법 (How to use float-right for right align in bootstrap)

맥(Mac)에서 MySql 사용 시 Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) 오류가 발생하는 경우 해결 방법

HTML, CSS - footer fixed (foot 하단 고정 시키기)