What does return unless nil do in Ruby?

What does return unless nil do in Ruby?

Another useful thing that Ruby does is, instead of returning true or false from boolean operations it just returns the last operand it evaluates. So in this case if expensive_operation_1 returns nil, it will then call expensive_operation_2, and if that returns a value (that isn’t falsy), the whole expression will just evaluate to that value.

Why do I get undefined method for nil in Ruby?

This will often lead to all sorts of problems since we expect the method we called to return a valid value instead of a nil. To avoid this error, you will need to check if you have a nil value before you call a method on it. If you don’t want to get the “undefined method for nil:NilClass” error try this…

When to reject a map block in Ruby?

I’d like to remind people that if you’re getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you’ve got code smell and need to rethink your logic. Then don’t. Instead, prior to the map, reject the stuff you don’t want or select what you do want:

Where can I find the nil of a number?

Another place where you can find nil is with the puts & print methods. These two methods always return nil. I mention this because I have seen some of my students try something like this: Which results in numbers being [nil, nil, nil]. The solution in this case is to simply remove the puts from inside the block.

Is it better to return from a function early or late?

Functions should of course not be so long in the first place, and if you have a huge switch statement your code is probably also badly factored. Early returns for-the-win. They can seem ugly, but much less ugly than big if wrappers, especially if there’s multiple conditions to check.

Which is better early return or for the win?

Early returns for-the-win. They can seem ugly, but much less ugly than big if wrappers, especially if there’s multiple conditions to check. I use both.

Do you put if return or if Precond return?

By putting if (!precond) return;, you are visually listing all preconditions. Using the large “if-else” block may increase indent overhead (I forgot the quote about 3-level indents). I prefer to keep if statements small. I’d choose what you described as “early return”.