Search ruby hash for empty value

Try this:

def hash_has_blank hsh
    hsh.values.any? &:empty?
end

Or:

def hash_has_blank hsh
    hsh.values.any?{|i|i.empty?}
end

If you are using an old 1.8.x Ruby


I hope you're ready to learn some ruby magic here. I wouldn't define such a function globally like you did. If it's an operation on a hash, than it should be an instance method on the Hash class you can do it like this:

class Hash
  def has_blank?
    self.reject{|k,v| !v.nil? || v.length > 0}.size > 0
  end
end

reject will return a new hash with all the empty strings, and than it will be checked how big this new hash is.

a possibly more efficient way (it shouldn't traverse the whole array):

class Hash
  def has_blank?
    self.values.any?{|v| v.nil? || v.length == 0}
  end
end

But this will still traverse the whole hash, if there is no empty value

I've changed the empty? to !nil? || length >0 because I don't know how your empty method works.


If you just want to check if any of the values is an empty string you could do

h.has_value?('')

but your function seems to work fine.

Tags:

Ruby