Search code examples
rubymethodschaining

Ruby chaining methods with if-statement


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


Solution

  • 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