Only
false
and nil
are treated as being false in a boolean context. All other values are treated as being true.and
, &&
, or
, and ||
all return operands. Bot and
and &&
return their first argument if it is false. Otherwise, they evaluate and return their second argument. Similarly, both or
and ||
return their first argument unless it is false, in which case they evaluate and return their second argument.The word forms of the logical operators (
and
, or
and not
) have a lower precedence than the corresponding symbol forms (&&
, ||
, and !
).Equality testing:
Ruby has three main equality test methods,
==
, eql?
and equal?
. They are defined in the Object
class and in the Object
class, all three methods do exactly the same thing, they test if two objects are exactly the same object. However, in other classes, they are usually redefined with different semantics:==
Test for equal valueeql?
True if the receiver and argument have both the same type and equal values.1 == 1.0
returnstrue
, but1.eql?(1.0)
isfalse
.equal?
True if the receiver and argument have the same object ID.
===
, which is used to compare each of the items with the target in the when
clause of a case
statement. The ===
operator is defined in Class
to test whether the argument is an instance of the receiver or one of its superclasses. So you can use it to test the class of objects.Python:
More values are considered false in Python:
None
False
- zero of any numeric type, for example,
0
,0L
,0.0
,0j
. - any empty sequence, for example,
''
,()
,[]
. - any empty mapping, for example,
{}
. - instances of user-defined classes, if the class defines a
__nonzero__()
or__len__()
method, when that method returns the integer zero orbool
valueFalse
.
In Python,
==
is similar to ==
in Ruby for numeric types and different string types (str
and unicode
) in that it only compares the values, but not the types, e.g. 1 == 1.0
returns True
. But for objects of other types, ==
is similar to eql?
in Ruby because both types and values have to be equal for it to return True
. The object identity test is
is the same to equal?
in Ruby.To check if an object is an instance of a type (class), use
isinstance(object, type_name)
.
No comments :
Post a Comment