Liroy Leshed Liroy Leshed - 7 months ago 21
Ruby Question

Grammar in Ruby "&&="

What does

&&=
mean in the following method?

records.each do |record|
raise_on_type_mismatch!(record)
add_to_target(record) do |rec|
result &&= insert_record(rec, true, should_raise) unless owner.
new_record?
end
end

Answer

a &&= b is a short form (aka syntactic sugar) for:

a && a = b

This short form is provided for operators (including but not possibly limited to) +, -, /, *, %, **, ^, <<, >>, &, |, &&, || (credits to @Stefan for full list of supported operators shortcuts):

a = 5
a += 5
#⇒ 10

a = true
a &&= true
#⇒ true
a &&= false
#⇒ false

&& is a logical and aka “conjunction” as opposed to || which is logical or aka “disjunction.”