Question

I have seen and used by myself lots of ||= in Ruby code, but I have almost never seen or used &&= in practical application. Is there a use case for &&=?

Was it helpful?

Solution 3

Validation of the document such as,

a = {'a' => ['string',123]}

where the element in a['a'] should be a String. To validate them, I think you can use,

def validate(doc, type)
  valid = true
  doc.each{|x|
    valid &&= x.is_a? type
  }
  valid    
end

1.9.3p392 :010 >   validate(a['a'],String) => false

OTHER TIPS

Not to be glib, but the obvious use case is any time you would say x && foo and desire the result stored back into x. Here's one:

list = [[:foo,1],[:bar,2]]
result = list.find{ |e| e.first == term }
result &&= result.last  # nil or the value part of the found tuple

any sort of iteration where you want to ensure that the evaluation of a boolean condition on all elements returns true for all the elements.

e.g.

 result = true
 array.each do |elem|
   # ...

   result &&= condition(elem)   # boolean condition based on element value
 end
 # result is true only if all elements return true for the given condition
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top