LightBox
LightBox

Reputation: 3425

Ruby - return false unless a value is true in which case return the value

If a = false and b = 2 is there a concise way to accomplish this? Using just return a unless b returns 'nil' instead of '2'.

I have

def checkit
  return a unless b
  b
end

Will this statement call b twice?

A real life case for this is:

def current_user
  @current_user ||= authenticate_user
end

def authenticate_user
    head :unauthorized unless authenticate_from_cookie 
end

def authenticate_from_cookie
  .
  if user && secure_compare(user.cookie, cookie)
    return user
  else
    return nil
  end
end

Upvotes: 5

Views: 7892

Answers (2)

Farrukh Abdulkadyrov
Farrukh Abdulkadyrov

Reputation: 717

Try this:

 ( b == true ) ? a : false

where a is a value you need to return

Upvotes: 4

Daniël Knippers
Daniël Knippers

Reputation: 3055

I do not know why you have false stored in the variable a, so I omitted that. As I understand, you want to pass a value to the method checkit, which should return the value if its boolean value is true (which means everything except values nil and false), and otherwise return the value. In that case, just use this:

def checkit(value)
  value || false
end

checkit(1)       # => 1
checkit(false)   # => false
checkit('value') # => "value"
checkit(nil)     # => false

Upvotes: 2

Related Questions