Question

I have several sections of code that have several grouped "or" conditionals, like this:

def some_method
 first_var || second_var || false
end

What's the best way to avoid this if there is one? I want it to remain compact and efficient though. My guess is that this is as good as it gets, but there's something in the back of mind that keeps saying that there must be some better way.

Was it helpful?

Solution

If you don't want to add || false, but you don't want nil to be returned, you can do the following:

def some_method
  !!(first_var || second_var)
end

This way, if the return value of (first_var || second_var) is nil a false will be returned:

!!true
# => true
!!false
# => false
!!nil
# => false

OTHER TIPS

You could wrap it inside an array and use any?

  def some_method
    [first_var, second_var].any?
  end

What you can do is remove the un-necessary false in the end as it will automatically evalute to false if first_var and second_var are false, rest looks like good to go:

def some_method
 first_var || second_var
end

If you are using some_method in a conditional statement than returning nil will also act as false, otherwise your original code is also clean and clear unless you want to so some fancy stuff, however I feel that will be overkill.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top