ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

assignment in conditional ternary

Open MathieuDerelle opened this issue 7 years ago • 5 comments

Should assignment in conditional ternary be avoided ?

something like this

condition ? self.foo = bar : self.foo2 = bar2

it's dealing with operator precedence and it is less clear than

if condition
  self.foo = bar 
else
  self.foo2 = bar2
end

that we are modifying some state

MathieuDerelle avatar Feb 16 '18 14:02 MathieuDerelle

Conditional ternary should be used when the operations after the if or else statements are simple enough to be put into one line. The assignment operation is one of the simplest operations so it seems natural to use the simplified conditional in Ruby instead of a classic if/else.

khmariem avatar Jul 18 '18 22:07 khmariem

Interesting question. I think @khmariem is right in principle, but in practice I don't think I've seen many assignments in ternary ops. I'd love to hear what others think about this or get some data from real-life usages in projects.

bbatsov avatar Jun 12 '19 08:06 bbatsov

As someone who recently encountered basically this exact example, my opinion is that assignments should stay out of ternary, mainly because of humans difficulty in parsing statements effectively - I feel there are too many chances to misunderstand what the statement is trying to communicate.

pnomolos avatar Jul 15 '19 23:07 pnomolos

There is this https://github.com/rubocop-hq/ruby-style-guide#nested-ternary-operators

Use one expression per branch in a ternary operator

Is it sufficient to clarify that an "expression" should not have side effects? (see https://en.wikipedia.org/wiki/Expression_(computer_science)#Side_effects_and_elimination) However, such wording would restrict the use of method calls in branches, as methods can have side effects as well.

Frankly, I'm puzzled to tell if foo(bar) falls into "one expression" category or not.

pirj avatar Feb 22 '21 21:02 pirj

Assignment in ternaries should definitely be avoided if they are assigning to the same variable, eg

condition ? self.foo = bar : self.foo = bar2

vs

self.foo = condition ? bar :  bar2

sumirolabs avatar Jan 11 '22 23:01 sumirolabs