I’m learning ruby and I got stuck with probable simple problem. There is the code:
str = 'abc'
a = 1
b = 2
a = str.reverse if str.size > 3
b = (str.reverse if str.size > 3)
p a
p b
Output:
1
nil
Can somebody tell me what these parentheses change in return value ?
Is it kind of “block” of code ?
They are two different statements.
The first one is a conditional assignment:
The
ifapplies to the whole line. Ifstr.sizeis not greater than 3, then absolutely nothing happens;ais not touched at all. You could also write it this way:Being able to stick the
ifon the end just lets you do it in one line instead of a block.The second one is an assignment of a conditional value.
The value of
bwill always be changed in this case, no matter what; the value ofstr.sizejust determines what it is changed to. You could also use the block-form ofifhere:The important difference is that the assignment to
bhappens outside theif, so it’s not conditional; it always happens.Parentheses don’t create blocks, but they do determine precedence. Whenever you have a statement that could be interpreted multiple ways depending on the order in which things happen, what actually happens is determined by precedence rules. For instance, standard arithmetic rules tell us that this is true:
The answer isn’t 20 because multiplication has precedence over addition. Parentheses let you change that; the above is equivalent to
and if you want the answer to be 20, then you could write this instead:
Same thing goes for Ruby. Without parentheses, the first line is equivalent to this parenthesized version:
which makes it clear that the assignment is what is guarded by the condition, not just the value being assigned.