I have the following:
def method(integer) a = 3+integer a += 10 if "one"<"another" end
Can I write it in one line somehow with chaining methods?
Something like a = 3+f += 10 if "one"<"another"?
a = 3+f += 10 if "one"<"another"
Since and or && both use short-circuit evaluation, you could use:
and
&&
(a = 3+integer) and ("one"<"another") and (a += 10)
It says in 'Using “and” and “or” in Ruby':
and is useful for chaining related operations together until one of them returns nil or false Another way of thinking about and is as a reversed if statement modifier
and is useful for chaining related operations together until one of them returns nil or false
Another way of thinking about and is as a reversed if statement modifier
a= 3+ integer + ("one"<"another" ? 10 : 0)
3+ integer will add 3 to integer value and ("one"<"another" ? 10 : 0) will return 10 if condition is true otherwise will return 0.
3+ integer
3
integer
("one"<"another" ? 10 : 0)
You could do it in one line using the ternary operator:
def method(integer) a = integer + ("one"<"another" ? 13 : 3) end
Make sure you don't hurt the readability of the code when you do that, though.
Copyright © 2021 Jogjafile Inc.
Since
and
or&&
both use short-circuit evaluation, you could use:It says in 'Using “and” and “or” in Ruby':