Noob Question on Conditions

Hi,

So I’ve got a bit of code here:

@is_Gnome = true
@is_Dwarf = false
@is_Man1 = false
@is_Man2 = false

def str_trait
if @is_Gnome == true
return 10
elsif @is_Dwarf == true
return 20
else
return 0
end
end

For some reason it’s returning 0 regardless of conditions, unless I
change the if condition to “!= false”, in which case it always returns
10.

I have no clue why this is happening.

@… are instance variables. If you use with a class, it works:

class Creature
def initialize
@is_Gnome = true
@is_Dwarf = false
@is_Man1 = false
@is_Man2 = false
end
def str_trait
if @is_Gnome == true
return 10
elsif @is_Dwarf == true
return 20
else
return 0
end
end
end

p Creature.new.str_trait

This prints “10”.

Dansei Yuuki wrote in post #1181824:

@… are instance variables. If you use with a class, it works:

Yuuki-san, I don’t quite follow your argument here. I admit that the
usage of instance variables (and the whole programming style, including
the way the conditions are written) are a bit unusual, but this should
not be incorrect here. The code runs in the top level environment, where
self is well defined. The variable @is_Gnome etc. would then be new
instance variables in class :Object.

Indeed, if I print the result of str_trait, I do get 10 as a result,
and not 0, as the OP claimed.

Ronald