Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assignment in a conditional clause good ruby style?

In order to write more concisely, rather than do this:

test_value = method_call_that_might_return_nil() if test_value   do_something_with test_value end 

I've been assigning in the conditional:

if test_value = method_call_that_might_return_nil()   do_something_with test_value end 

Is this bad style? The still-more-concise syntax:

do_something_with test_value if test_value = method_call_that_might_return_nil() 

is not allowed, as discussed in another SO question, and will remain that way in 1.9, according to Matz (http://redmine.ruby-lang.org/issues/show/1141).

Given the possible confusion of assignment and comparison, does this make it too hard to read the code?

like image 907
TimH Avatar asked Dec 27 '09 18:12

TimH


People also ask

What does assignment in conditional expression mean?

It means you assign a value where you're meant to compare two values.

What is ||= in Ruby?

||= is called a conditional assignment operator. It basically works as = but with the exception that if a variable has already been assigned it will do nothing. First example: x ||= 10. Second example: x = 20 x ||= 10. In the first example x is now equal to 10.


1 Answers

It is GOOD style to use assignments in conditionals. If you do so, wrap the condition in parentheses.

# bad (+ a warning) if v = array.grep(/foo/)   do_something(v)   # some code end  # good (MRI would still complain, but RuboCop won't) if (v = array.grep(/foo/))   do_something(v)   # some code end  # good v = array.grep(/foo/) if v   do_something(v)   # some code end 

See the community style guide for more information

like image 57
Devon Parsons Avatar answered Sep 17 '22 00:09

Devon Parsons