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?
It means you assign a value where you're meant to compare two values.
||= 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.
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
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