sank sank - 1 year ago 81
Ruby Question

What the does the line if a = b mean in ruby code?

I am trying to understand a particular line in the following piece of code:

def roman_to_integer(roman_string)
prev = nil
roman_string.to_s.upcase.split(//).reverse.inject(0) do
|running_sum, digit|
if digit_value = DIGITS[digit]
if prev && prev > digit_value
running_sum -= digit_value
running_sum += digit_value
prev = digit_value

Can someone please help me understand when the line if digit_value = DIGITS[digit] means? are we assigning the value corresponding to the key 'DIGIT' from the hash to the digit_value here?

Answer Source

are we assigning the value

Yes, we are. And we also check the truthiness of the operation. Assignment operator returns the value that was assigned. Now, if it was a digit, it will be a truthy result and control will enter the if.

If DIGITS[digit] returns nil or false, it will be assigned to digit_value and also it will also become result of the assignment operation. Those values are falsey, so we would enter the else, if we had one there. But we don't, so we just skip the if.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download