← Back to Upcase

Conditional Assignments (assign_to_condition vs assign_inside_condition)


(Edwin Maldonado) #1

Hey everyone!

Maybe it’s just a pure style thing but I prefer to use Conditional Assignments as “assign_inside_condition” like:

if foo
  bar = 1
else
  bar = 2
end

case foo
when 'a'
  bar += 1
else
  bar += 2
end

if foo
  some_method
  bar = 1
else
  some_other_method
  bar = 2
end

It is super easy to read and there are no surprises with assignations.

However … I’m using Rubocop and it seems it supports both assign_to_condition and assign_inside_condition. And I started to wondering if there is any real advantage of using assign_to_condition … In my very own personal opinion I find this a bit ugly and hard to read … but maybe I’m wrong …

Maybe I’m just not happy having it like:

bar = if foo
        1
      else
        2
      end

bar += case foo
       when 'a'
         1
       else
         2
       end

bar << if foo
         some_method
         1
       else
         some_other_method
         2
       end

What do you guys think? And What do you usually use?

Rubocop ConditionalAssignments

Thanks!


(Joel Quenneville) #2

I think it comes down to whether you treat conditionals as expressions that return values versus statements that have side effects.

Among other things, when I write Ruby I try to:

I do agree with you that assigning a conditional to a variable looks ugly :smile:

I’d probably extract the conditional in your example to its own function:

def bar(foo)
  if foo
    1
  else
    2
  end
end

A more complex method might look like:

def bar(foo)
  baz = some_other_expression

  if foo
    1 + baz
  else
    2 + baz
  end
end

I definitely avoid the assign_inside_condition style because I write my conditionals as expressions. However, since I usually extract conditionals to their own methods (or at least have them at the end of my method), I pretty much never assign conditionals to variables either.


(Edwin Maldonado) #3

This expressions vs statements difference makes a lot of sense!

Thanks for adding the article links, I will definitely take a look. :+1: