Donovan Thomson
Donovan Thomson

Reputation: 2525

Determine if a hash is a nested hash in Ruby

Is there a way to determine if a hash is a nested hash in ruby ?

For example

a = { a: 1, b: 2, c: 2 }

should return false

a = { a: {a1: 1, a2: 2}, b: {b1: 1}, c: 2 }

should return true

Upvotes: 0

Views: 73

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51161

You can check it by iterating over your hash values with Hash#values method:

a.values.any? { |v| v.is_a?(Hash) }

Upvotes: 1

Alex Antonov
Alex Antonov

Reputation: 15156

a.any? { |_, v| v.is_a?(Hash) }

Upvotes: 4

Related Questions