"1", "b" => "", "c" => "2"} Now I have a ruby ​​functi...">

Finding a ruby ​​hash for an empty value

I have a ruby ​​hash like this
h = {"a" => "1", "b" => "", "c" => "2"}
Now I have a ruby ​​function that evaluates this hash and returns true if it finds a key with an empty value. I have the following function that always returns true, even if all the 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? Please, help

Thanks Abhi

+5
source share
4 answers

I hope you are ready to learn ruby ​​magic here. I would not call such a function globally, like you. If it is a hash operation, than it should be an instance method in 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 empty lines, and it will check how big this new hash is.

( ):

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

,

empty? !nil? || length >0, , empty.

+8

:

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

:

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

1.8.x Ruby

+17

, - ,

h.has_value?('')

.

+4

. , - . ? , Hash. , .

-, , , , . "", , Item , .

class MyItem < Hash

  def valid?
    !invalid?
  end

  def invalid?
    values.any?{|i| i.empty?}
  end
end

The fact is that if you can install a dictionary that makes sense in your domain, your code will be cleaner and more understandable. Using a hash is just a means to an end, and you would be better off using more descriptive domain-specific terms.

Using the above example, you can:

my_item = MyItem["a" => "1", "b" => "", "c" => "2"]

my_item.valid? #=> false
+4
source

All Articles