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?
ifstatement, it's anifexpression, which is precisely why this works in the first place. (In fact, there are no statements in Ruby, everything is an expression and everything returns a value.)x = case(y); when ....andx = (y=3) ? 3 : 1, which are commonplace.