Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement after variable assignment - how common?

Tags:

ruby

I was recently discussing the following Ruby syntax with a colleague:

value = if a == 0
          "foo"
        elsif a > 42
          "bar"
        else
          "fizz"
        end

I haven't seen this sort of logic much personally, but my colleague notes that it's actually a fairly common Rubyism. I tried googling the topic and found no articles, pages, or SO questions discussing it, making me believe it might be a very matter-of-fact technique. Another colleague, however, finds the syntax confusing and would instead write the above logic like this:

if a == 0
  value = "foo"
elsif a > 42
  value = "bar"
else
  value = "fizz"
end

The disadvantage there being the repeated declarations of value = and the loss of an implicit else nil, if we wanted to use it. This also feels like it lines up with a lot of other syntactical sugar features found in Ruby.

My question is, how common is this technique in Ruby? Is there some sort of consensus on whether the community feels like this should be used or avoided?

like image 939
Argus9 Avatar asked Jun 09 '17 19:06

Argus9


2 Answers

value = if condition
          x
        else
          y
        end

is common. It lends itself to cleaning up this situation:

if condition
  value = x
else
  value = y
end

Have a look at this Ruby style guide. It's a popular guide in how Ruby code should be written.

https://github.com/bbatsov/ruby-style-guide#use-if-case-returns

like image 162
Charlie Avatar answered Nov 15 '22 09:11

Charlie


The fact that if and case return values makes for some very tight, tidy, and yet still understandable code. It's a common pattern in Ruby when you're dealing with assignment through branching.

The way I tend to approach formatting these is to apply a level of indentation to make the assignment clear, but not overly "push" the code in too far:

value =
  if a == 0
    "foo"
  elsif a > 42
    "bar"
  else
    "fizz"
  end

Or if you want a case:

value =
  case
  when a == 0
    "foo"
  when a > 42
    "bar"
  else
    "fizz"
  end

In many cases you'll see a method that has an if as the body to determine the result:

def value(a)
  if a == 0
    "foo"
  elsif a > 42
    "bar"
  else
    "fizz"
  end
end

Then there's no quirky indentation necessary.

like image 28
tadman Avatar answered Nov 15 '22 09:11

tadman