Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search ruby hash for empty value

Tags:

ruby

I have a ruby hash like this
h = {"a" => "1", "b" => "", "c" => "2"}
Now I have a ruby function which evaluates this hash and returns true if it finds a key with an empty value. I have the following function which always returns true even if all keys in the hash are not empty

def hash_has_blank(hsh)  
  hsh.each do |k,v|  
    if v.empty?  
      return true  
    end  
  end
  return false
 end

What am I doing wrong here?

like image 263
eabhvee Avatar asked Sep 07 '10 11:09

eabhvee


2 Answers

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

like image 109
Nakilon Avatar answered Nov 06 '22 10:11

Nakilon


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.

like image 44
jigfox Avatar answered Nov 06 '22 11:11

jigfox