artichoke_backend::convert

Function implicitly_convert_to_int

Source
pub fn implicitly_convert_to_int(
    interp: &mut Artichoke,
    value: Value,
) -> Result<i64, Error>
Expand description

Attempt to implicitly convert a Value to an integer.

Attempt to extract an i64 from the given Value by trying the following conversions:

  • If the given value is a Ruby integer, return the inner integer.
  • If the given value is nil, return a TypeError.
  • If the given value responds to the :to_int method, call value.to_int:
    • If value.to_int raises an exception, propagate that exception.
    • If value.to_int returns a Ruby integer, return the inner integer.
    • If value.to_int returs any other type, return a TypeError.
  • If the given value does not respond to the :to_int method, return a TypeError.

Floats and other numeric types are not coerced to integer by this implicit conversion.

§Examples

let mut interp = artichoke_backend::interpreter()?;
// successful conversions
let integer = interp.convert(17);
let a = interp.eval(b"class A; def to_int; 3; end; end; A.new")?;

assert!(matches!(
    implicitly_convert_to_int(&mut interp, integer),
    Ok(17)
));
assert!(matches!(implicitly_convert_to_int(&mut interp, a), Ok(3)));

// failed conversions
let nil = Value::nil();
let b = interp.eval(b"class B; end; B.new")?;
let c = interp.eval(b"class C; def to_int; nil; end; end; C.new")?;
let d = interp.eval(b"class D; def to_int; 'not an integer'; end; end; D.new")?;
let e = interp.eval(b"class E; def to_int; 3.2; end; end; E.new")?;
let f = interp
    .eval(b"class F; def to_int; raise ArgumentError, 'not an integer'; end; end; F.new")?;

assert!(implicitly_convert_to_int(&mut interp, nil).is_err());
assert!(implicitly_convert_to_int(&mut interp, b).is_err());
assert!(implicitly_convert_to_int(&mut interp, c).is_err());
assert!(implicitly_convert_to_int(&mut interp, d).is_err());
assert!(implicitly_convert_to_int(&mut interp, e).is_err());
assert!(implicitly_convert_to_int(&mut interp, f).is_err());

§Errors

This function returns an error if:

  • The given value is nil.
  • The given value is not an integer and does not respond to :to_int.
  • The given value is not an integer and returns a non-integer value from its :to_int method.
  • The given value is not an integer and raises an error in its :to_int method.