Ruby: Use the return of the conditional for variable assignment and comparison
Asked Answered
F

1

44

I have a method and in order to check whether it is being passed a block, I do the following:

if block_given?
    res = yield(array[i], array[i+1])
  else
    res = array[i] - array[i+1]
  end

However RuboCop is giving me a warning which I don't really understand in the if block_given? line:

Use the return of the conditional for variable assignment and comparison

Is there any other more rubyist way of doing this?

Thanks

Forficate answered 11/2, 2018 at 11:29 Comment(0)
P
78

What the warning is telling you to do is:

res = if block_given?
        yield(array[i], array[i+1])
      else
        array[i] - array[i+1]
      end

That is, having a single assignment instead of two (or even more).

Precautionary answered 11/2, 2018 at 11:36 Comment(5)
maybe res = block_given? ? yield(array[i], array[i + 1]) : array[i] - array[i + 1] would be valid too?Forficate
Sure, but this one seems to be more readable. Specially if there are multiple branches (think of nesting ? :).Benzo
also, alignment is important for Rubocop.Atreus
noloman, yes, and I think that’s preferable. The Ruby Style Guide favours the use of ternery expressions, provided (as here) there is only one expression per branch and those expressions are not themselves terneries. I agree.Uranian
just watch out to Rubocop indentation rules. Depending on your setup, else and end must be aligned to res and not to ifCarlotacarlotta

© 2022 - 2024 — McMap. All rights reserved.