In irb we have:
1 + true
=> TypeError: true can’t be coerced into Fixnum
In rbx we have:
1 + true
=> 2
There are the following methods for + in Fixnum:
public static object Add(int self, int other)
public static double Add(int self, double other)
public static object Add(CodeContext/!/ context, object self, object
other)
I expected that passing a bool into + operator would have ended up at
the
third overload, which would give the correct behaviour when it tries to
coerce on the bool. But it actually gets mapped to the first overload
and
there is an implicit conversion of true to 1. You can see this in the
resulting AST dump:
(FixnumOps.Add)(
(.bound $arg0),
(Converter.ConvertToInt32)(
(Object)(.bound $arg1),
),
)
After some digging I found this method in Ruby.Runtime.Converter:
private static bool HasImplicitNumericConversion(Type fromType,
Type
toType) {
if (fromType.IsEnum) return false;
if (fromType == typeof(BigInteger)) {
if (toType == typeof(double)) return true;
if (toType == typeof(float)) return true;
if (toType == typeof(Complex64)) return true;
return false;
}
if (fromType == typeof(bool)) {
if (toType == typeof(int)) return true;
return HasImplicitNumericConversion(typeof(int),
toType);
}
...
Here you can see that bool is automatically converted to an int. Is
this
correct behaviour? I appreciate that we can take any non-nil value as
true
and nil as false but not the other way round.
ASIDE: In fact all three methods are added as “Applicable Targets” but
the
int version gets there first. Is there a heuristic for the order in
which
overloads are considered?
Regards,
Pete