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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With