Ruby chaining methods with if-statement

103 Views Asked by At

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"?

3

There are 3 best solutions below

1
On BEST ANSWER

Since and or && both use short-circuit evaluation, you could use:

(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

1
On
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.

0
On

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.