Ryan
Ryan

Reputation: 688

Chef Ruby dig Wrong Number of Arguments

I am trying to do something very simple with Chef/Ruby. All I want to do is check if a key in my hash is nil in a safe and clean manner.

Here is my code:

if node.dig('k1', 'k2', 'k3').nil?
  myvar1 = node['kA']['kB']['kC']
else
  myvar1 = node['k1']['k2']['k3']
end

However, I am getting a Recipe Compile Error stating:

ArgumentError
-------------
wrong number of arguments (given 1, expected 0)

What am I doing wrong here? I have read the documentation for dig here: http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig but it doesn't seem to be helping

I am using Ruby 2.3

Upvotes: 3

Views: 1463

Answers (2)

Ryan
Ryan

Reputation: 688

Turns out node is not a hash, but rather a node object, so .dig() does not work. I ended up using the following:

if node.read('k1', 'k2', 'k3').nil?
  myvar1 = node['kA']['kB']['kC']
else
  myvar1 = node['k1']['k2']['k3']
end

Upvotes: 2

coderanger
coderanger

Reputation: 54249

We didn’t add that to the API supported by the node above the because it overlapped with the existing node.read method which is what you want to use here. It looks like a hash, but only supports a subset of the methods.

EDIT: Now that I'm not on mobile the full code you want is probably:

node.read('k1', 'k2', 'k3') || node.read('kA', 'kB', 'kC')

Unless false is a valid value.

Upvotes: 4

Related Questions