If expression after assigning a variable - how often?

I recently discussed the following Ruby syntax with a colleague:

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

I have not seen such logic in person, but my colleague notes that this is actually quite common rubism. I tried to understand this topic and did not find the articles, pages or questions that discussed it, making me believe that this could be very important. However, another colleague considers the syntax confusing and would instead write the following logic:

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

The disadvantage is the repeated declaration of value = and the loss of the implicit else nil if we want to use it. It also seems to combine with many of the other syntactic properties of sugar found in Ruby.

My question is: how common is this method in Ruby? Is there any consensus on whether this community should be used or avoided?

+5
source share
2 answers

The fact that the return values โ€‹โ€‹of if and case return some very tough, neat, but still understandable code. This is a common pattern in Ruby when you are dealing with assignment via branching.

The way I tend to get closer to formatting is to use the indentation level to make the assignment clear, but not push the code too far:

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

Or if you want case :

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

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

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

Then there is no fancy indentation.

+4
source
 value = if condition x else y end 

is common. This lends itself to clearing this situation:

 if condition value = x else value = y end 

Take a look at this Ruby style guide. This is a popular guide to writing Ruby code.

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

+6
source

Source: https://habr.com/ru/post/1268714/


All Articles