Search code examples
rubycoding-style

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?


Solution

  • 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