End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
BigDecimal#coerce
coerce(p1)
ext/bigdecimal/bigdecimal.c
View on GitHub ↗
static VALUE
BigDecimal_coerce(VALUE self, VALUE other)
{
ENTER(2);
VALUE obj;
Real *b;
if (RB_TYPE_P(other, T_FLOAT)) {
GUARD_OBJ(b, GetVpValueWithPrec(other, DBLE_FIG, 1));
obj = rb_assoc_new(ToValue(b), self);
}
else {
if (RB_TYPE_P(other, T_RATIONAL)) {
Real* pv = DATA_PTR(self);
GUARD_OBJ(b, GetVpValueWithPrec(other, pv->Prec*VpBaseFig(), 1));
}
else {
GUARD_OBJ(b, GetVpValue(other, 1));
}
obj = rb_assoc_new(b->obj, self);
}
return obj;
}
The coerce method provides support for Ruby type coercion. It is not enabled by default.
This means that binary operations like + * / or - can often be performed on a BigDecimal and an object of another type, if the other object can be coerced into a BigDecimal value.
e.g.
Example
a = BigDecimal("1.0") b = a / 2.0 #=> 0.5
Note that coercing a String to a BigDecimal is not supported by default; it requires a special compile-time option when building Ruby.