0

I have a YAML file like this:

options:
    some_option: 'foo'

which I load as a hash yaml, on which I want to be able to use include? to get a boolean telling whether a key exists in it or not.

To get the sub-keys of options, I would normally use yaml["options"]["some_option"], however how would I find out if the YAML hash includes ["options"]["some_option"]? You can't do something like:

if yaml.include? "options"["some_option"] # or
if yaml.include? ["options"]["some_option"] # or even
if yaml.include? yaml["options"]["some_option"]

Is there a way to retrieve the sub-key of options in the YAML hash?

sawa
  • 165,429
  • 45
  • 277
  • 381
beakr
  • 5,709
  • 11
  • 42
  • 66

2 Answers2

5

Depending on the expected values in the yaml file, you can just use Ruby's typecasting:

if yaml["options"] && yaml["options"]["some_option"]

If yaml["options"] doesn't exist, it will return nil, which will short circuit the if statement and return false.

Obviously, this won't work as an existence check if a valid value for "some_option" is falsey. You'll need to explicitly use has_key?:

if yaml.has_key?("options") && yaml["options"].has_key?("some_option")
Cade
  • 3,151
  • 18
  • 22
1
yaml["options"].include? "some_option"

And if it's possible for "options" to not be set:

(yaml["options"] || {}).include? "some_option"
Nevir
  • 7,951
  • 4
  • 41
  • 50