'if not or' not working in Ruby -


i have code in ruby:

if @pass.nil?         badpass(@nick) elsif not clt.correctpassword?(@nick, @pass)         badpass(@nick) 

i wanted condense single line tried writing as:

if not clt.correctpassword?(@nick, @pass) or @pass.nil?         badpass(@nick) 

but badpass(@nick) doesn't triggered either cases, whereas works in both cases in top example.

why happen?

in revised code tests in opposite order original. it's if had written:

if not clt.correctpassword?( @nick, @pass )     badpass( @nick ) elsif @pass.nil?     badpass( @nick ) end 

put tests in same order original , work original:

if @pass.nil? or not clt.correctpassword?( @nick, @pass )     badpass( @nick ) end 

remember ruby, many other languages, uses short circuit evaluation logical operators and, or, && , ||. means evaluates expression left of operator first, , evaluates expression right of operator if needs to.

btw, many rubyists write way instead:

badpass( @nick ) if @pass.nil? or not clt.correctpassword?( @nick, @pass ) 

that same thing; it's matter of style prefer.

if .correctpassword? method code can modify, nice option add nil test @ beginning of method. in fact, may test nil on both nick , pass:

def correctpassword?( nick, pass )     return false if nick.nil? or pass.nil?     ... rest of code here ... end 

then when call method can use:

if not clt.correctpassword?( @nick, @pass )     badpass( @nick ) end 

or simple code:

badpass( @nick ) unless clt.correctpassword?( @nick, @pass ) 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -