An elegant way to check for nil and then check the value


#1

Hi,

I’m sure there’s an elegant way of doing the following:

def ep_is_sysop
    sysop = false
    if not @session['user'].nil?
        sysop = true if @session['user'].role == 'siteop'
    end
    sysop
end

Could you help me out?

Thanks!

Ivan V.


#2

On 24 Nov 2005, at 20:25, Iván Vega R. wrote:

I’m sure there’s an elegant way of doing the following:

def ep_is_sysop
sysop = false
if not @session[‘user’].nil?
sysop = true if @session[‘user’].role == ‘siteop’
end
sysop
end

Bit new to Ruby & Rails so I’m probably wrong, but I’d do

def ep_is_sysop
@session[‘user’] && @session[‘user’].role == ‘siteop’
end

Yours,
Craig

Craig W. | t: +44 (0)131 516 8595 | e: removed_email_address@domain.invalid
Xeriom.NET | f: +44 (0)709 287 1902 | w: http://xeriom.net


#3

I don’t know if this is any prettier but should be able to do:
(untested)

def ep_is_sysop
@session['user'] and @session['user'].role == 'siteop'
end

#4

How about

def ep_is_sysop
@session[‘user’] == ‘siteop’
end

nil compared to anythng will always yield false. qed


#5
Oops

#6

D’oh… Ruby is so simple and intuitive (for a “empty” brain that is)
that it actually makes it really hard for me… I’m always trying to do
stuff like I’d do in PHP or in other languages.

Thanks Craig & Robert. Hendie, that’s what I was doing at first, but I
think you’ve already realized why it doesn’t always work :slight_smile:

Ivan V.


#7

ivanvr wrote:

I’m sure there’s an elegant way of doing the following:

def ep_is_sysop
    sysop = false
    if not @session['user'].nil?
        sysop = true if @session['user'].role == 'siteop'
    end
    sysop
end

The answer was already given, but it may be worthwhile to check out

http://www.rubygarden.org/ruby?RubyIdioms

which addresses this, and many other useful bits.

Cheers,
-Tudor


#8

Using boolean short-circuit operators is not language specific. It’s
more
idiomatic. So, while you might be more likely to write the code below in
PHP, it would also work if you wrote:

function ep_is_sysop(){
return (!empty($_SESSION[‘user’] && $_SESSION[‘user’] == ‘siteop’);
}

That’s not to say you should use PHP. Just that you can use some similar
constructs to this.

cheers


#9

Tudor Oprea wrote:

end

Hey, that’s pretty useful information! Thanks!

Ivan V.