Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 365
noloman Avatar asked Feb 11 '18 11:02

noloman


1 Answers

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).

like image 166
ネロク・ゴ Avatar answered Sep 20 '22 23:09

ネロク・ゴ