Function magnus::scan_args::check_arity

source ·
pub fn check_arity<T>(len: usize, bounds: T) -> Result<(), Error>
where T: RangeBounds<usize>,
Expand description

Returns Err containing a Ruby ArgumentError if len is not within bounds.

§Panics

Panics if called from a non-Ruby thread. See Ruby::check_arity for the non-panicking version.

§Examples

use magnus::{
    define_global_function, eval, function, scan_args::check_arity, Error, RArray, RString,
    Value,
};

fn example(args: &[Value]) -> Result<RString, Error> {
    check_arity(args.len(), 2..5)?;
    RArray::from_slice(args).join(", ")
}

define_global_function("example", function!(example, -1));

assert_eq!(
    eval::<String>("example(1)").unwrap_err().to_string(),
    "wrong number of arguments (given 1, expected 2..4)"
);
assert_eq!(
    eval::<String>("example(1, 2, 3, 4, 5)")
        .unwrap_err()
        .to_string(),
    "wrong number of arguments (given 5, expected 2..4)"
);