Craig Williams

christian - husband - father - programmer - avid learner

Using Ruby’s Fetch Part I

| Comments

Skill level: beginner

When accessing an item in a Ruby hash, there are many times when we need to set a default value in the event the key is missing.

The || or Operator

One technique we can use is the || operator. I tend to stay away from this technique due to the sometimes unexpected behavior produced when using it with boolean values.

The following code is checking for the boolean_value key in the options hash. The expected behavior is that if the key is present, its value will be used. If the key is missing then the value will default to true

The problem here is that if the value is either false or nil the bool value will be set to true.

1
2
3
4
 otions = {boolean_value: false}
 bool = options[:boolean_value] || true

 bool #=> true

Fetch

Fetch is another technique and the one I use most of the time.