Sometimes, you want to use an if
/unless
modifier but the conditionally executed part includes a local variable that is to be defined within the condition. For example,
a = [1, 2, 3]
n = 3*(x**2) + 4*x + 5 if x = a[2]
m = 6*(y**2) + 7*y + 8 unless (y = a[0]).zero?
will give a parsing error because x
,y
is read before the if
/unless
modifier. In order to avoid that, I think it is pretty much common (at least for me) to use and
instead of if
and or
instead of unless
:
x = a[2] and n = 3*(x**2) + 4*x + 5
(y = a[0]).zero? or m = 6*(y**2) + 7*y + 8
Besides the fact that it does not raise an error, is there any difference? Is there any side effects in doing this? And, is there a better way?