Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 305
LightBox Avatar asked Mar 21 '14 15:03

LightBox


2 Answers

Try this:

 ( b == true ) ? a : false

where a is a value you need to return

like image 199
Farrukh Abdulkadyrov Avatar answered Oct 18 '22 19:10

Farrukh Abdulkadyrov


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
like image 36
Daniël Knippers Avatar answered Oct 18 '22 18:10

Daniël Knippers