Struct magnus::Ruby

source ·
pub struct Ruby(/* private fields */);
Expand description

A handle to access Ruby’s API.

Using Ruby’s API requires the Ruby VM to be initalised and all access to be from a Ruby-created thread.

This structure allows safe access to Ruby’s API as it should only be possible to aquire an instance in situations where Ruby’s API is known to be available.

Many functions that take Ruby values as arguments are available directly without having to use a Ruby handle, as being able to provide a Ruby value is ‘proof’ the function is being called from a Ruby thread. Because of this most methods defined on Ruby deal with creating Ruby objects from Rust data.


The methods available on Ruby are broken up into sections for easier navigation.

Implementations§

source§

impl Ruby

§Accessing Ruby

These functions allow you to obtain a Ruby handle only when the current thread is a Ruby thread.

Methods exposed to Ruby via the method, function or init macros can also take an optional first argument of &Ruby to obtain a Ruby handle.

source

pub fn get() -> Result<Self, RubyUnavailableError>

Get a handle to Ruby’s API.

Returns a new handle to Ruby’s API if it can be verified the current thread is a Ruby thread.

If the Ruby API is not useable, returns Err(RubyUnavailableError).

source

pub fn get_with<T>(value: T) -> Self
where T: ReprValue,

Get a handle to Ruby’s API.

Returns a new handle to Ruby’s API using a Ruby value as proof that the current thread is a Ruby thread.

Note that all Ruby values are Copy, so this will not take ownership of the passed value.

source

pub unsafe fn get_unchecked() -> Self

Get a handle to Ruby’s API.

§Safety

This must only be called from a Ruby thread - that is one created by Ruby, or the main thread after embed::init has been called - and without having released the GVL.

source§

impl Ruby

§Proc

Functions that can be used to create instances of Proc, Ruby’s representation of a block as an object.

See also the Proc type.

source

pub fn proc_new<R>(&self, block: fn(_: &[Value], _: Option<Proc>) -> R) -> Proc
where R: BlockReturn,

Create a new Proc.

As block is a function pointer, only functions and closures that do not capture any variables are permitted. For more flexibility (at the cost of allocating) see proc_from_fn.

§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let proc = ruby.proc_new(|args, _block| {
        let acc = i64::try_convert(*args.get(0).unwrap())?;
        let i = i64::try_convert(*args.get(1).unwrap())?;
        Ok(acc + i)
    });

    rb_assert!(ruby, "proc.call(1, 2) == 3", proc);

    rb_assert!(ruby, "[1, 2, 3, 4, 5].inject(&proc) == 15", proc);

    Ok(())
}
source

pub fn proc_from_fn<F, R>(&self, block: F) -> Proc
where F: 'static + Send + FnMut(&[Value], Option<Proc>) -> R, R: BlockReturn,

Create a new Proc.

See also proc_new, which is more efficient when block is a function or closure that does not capture any variables.

§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let mut count = 0;

    let proc = ruby.proc_from_fn(move |args, _block| {
        let step = i64::try_convert(*args.get(0).unwrap())?;
        count += step;
        Ok(count)
    });

    rb_assert!(ruby, "proc.call(1) == 1", proc);
    rb_assert!(ruby, "proc.call(1) == 2", proc);
    rb_assert!(ruby, "proc.call(2) == 4", proc);

    Ok(())
}
source§

impl Ruby

§Blocks

Functions to enable working with Ruby blocks.

See also the block module.

source

pub fn block_given(&self) -> bool

Returns whether a Ruby block has been supplied to the current method.

§Examples
use magnus::{function, rb_assert, Error, Ruby};

fn got_block(ruby: &Ruby) -> bool {
    ruby.block_given()
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function("got_block?", function!(got_block, 0));

    rb_assert!(ruby, "got_block? {} == true");
    rb_assert!(ruby, "got_block? == false");

    Ok(())
}
source

pub fn block_proc(&self) -> Result<Proc, Error>

Returns the block given to the current method as a Proc instance.

§Examples
use magnus::{block::Proc, function, rb_assert, Error, Ruby};

fn make_proc(ruby: &Ruby) -> Result<Proc, Error> {
    ruby.block_proc()
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function("make_proc", function!(make_proc, 0));

    rb_assert!(ruby, "make_proc {}.is_a?(Proc)");

    Ok(())
}
source

pub fn yield_value<T, U>(&self, val: T) -> Result<U, Error>
where T: IntoValue, U: TryConvert,

Yields a value to the block given to the current method.

Note: A method using yield_value converted to an Enumerator with to_enum/Value::enumeratorize will result in a non-functional Enumerator on versions of Ruby before 3.1. See Yield for an alternative.

§Examples
use magnus::{function, rb_assert, Error, Ruby, Value};

fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
    let _: Value = ruby.yield_value("foo")?;
    let _: Value = ruby.yield_value("bar")?;
    let _: Value = ruby.yield_value("baz")?;
    Ok(())
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function(
        "metasyntactic_variables",
        function!(metasyntactic_variables, 0),
    );

    let vars = ruby.ary_new();
    rb_assert!(
        ruby,
        "metasyntactic_variables {|var| vars << var} == nil",
        vars
    );
    rb_assert!(ruby, r#"vars == ["foo", "bar", "baz"]"#, vars);

    Ok(())
}
source

pub fn yield_values<T, U>(&self, vals: T) -> Result<U, Error>
where T: ArgList, U: TryConvert,

Yields multiple values to the block given to the current method.

Note: A method using yield_values converted to an Enumerator with to_enum/Value::enumeratorize will result in a non-functional Enumerator on versions of Ruby before 3.1. See YieldValues for an alternative.

§Examples
use magnus::{function, kwargs, rb_assert, Error, Ruby, Value};

fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
    let _: Value = ruby.yield_values((0, kwargs!("var" => "foo")))?;
    let _: Value = ruby.yield_values((1, kwargs!("var" => "bar")))?;
    let _: Value = ruby.yield_values((2, kwargs!("var" => "baz")))?;
    Ok(())
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function(
        "metasyntactic_variables",
        function!(metasyntactic_variables, 0),
    );

    let vars = ruby.ary_new();
    rb_assert!(
        ruby,
        "metasyntactic_variables {|pos, var:| vars << [pos, var]} == nil",
        vars
    );
    rb_assert!(
        ruby,
        r#"vars == [[0, "foo"], [1, "bar"], [2, "baz"]]"#,
        vars
    );

    Ok(())
}
source

pub fn yield_splat<T>(&self, vals: RArray) -> Result<T, Error>
where T: TryConvert,

Yields a Ruby Array to the block given to the current method.

Note: A method using yield_splat converted to an Enumerator with to_enum/Value::enumeratorize will result in a non-functional Enumerator on versions of Ruby before 3.1. See YieldSplat for an alternative.

§Examples
use magnus::{function, rb_assert, Error, Ruby, Value};

fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_new();
    ary.push(0)?;
    ary.push("foo")?;
    let _: Value = ruby.yield_splat(ary)?;
    let ary = ruby.ary_new();
    ary.push(1)?;
    ary.push("bar")?;
    let _: Value = ruby.yield_splat(ary)?;
    let ary = ruby.ary_new();
    ary.push(2)?;
    ary.push("baz")?;
    let _: Value = ruby.yield_splat(ary)?;
    Ok(())
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function(
        "metasyntactic_variables",
        function!(metasyntactic_variables, 0),
    );

    let vars = ruby.ary_new();
    rb_assert!(
        ruby,
        "metasyntactic_variables {|pos, var| vars << [pos, var]} == nil",
        vars
    );
    rb_assert!(
        ruby,
        r#"vars == [[0, "foo"], [1, "bar"], [2, "baz"]]"#,
        vars
    );

    Ok(())
}
source§

impl Ruby

§Core Classes

Functions to access Ruby’s built-in classes.

See also the class module.

source

pub fn class_array(&self) -> RClass

Return Ruby’s Array class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Array", klass = ruby.class_array());
    Ok(())
}
source

pub fn class_basic_object(&self) -> RClass

Return Ruby’s BasicObject class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == BasicObject",
        klass = ruby.class_basic_object()
    );
    Ok(())
}
source

pub fn class_binding(&self) -> RClass

Return Ruby’s Binding class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Binding", klass = ruby.class_binding());
    Ok(())
}
source

pub fn class_class(&self) -> RClass

Return Ruby’s Class class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Class", klass = ruby.class_class());
    Ok(())
}
source

pub fn class_complex(&self) -> RClass

Return Ruby’s Complex class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Complex", klass = ruby.class_complex());
    Ok(())
}
source

pub fn class_dir(&self) -> RClass

Return Ruby’s Dir class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Dir", klass = ruby.class_dir());
    Ok(())
}
source

pub fn class_encoding(&self) -> RClass

Return Ruby’s Encoding class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Encoding", klass = ruby.class_encoding());
    Ok(())
}
source

pub fn class_enumerator(&self) -> RClass

Return Ruby’s Enumerator class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Enumerator", klass = ruby.class_enumerator());
    Ok(())
}
source

pub fn class_false_class(&self) -> RClass

Return Ruby’s FalseClass class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == FalseClass",
        klass = ruby.class_false_class()
    );
    Ok(())
}
source

pub fn class_file(&self) -> RClass

Return Ruby’s File class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == File", klass = ruby.class_file());
    Ok(())
}
source

pub fn class_float(&self) -> RClass

Return Ruby’s Float class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Float", klass = ruby.class_float());
    Ok(())
}
source

pub fn class_hash(&self) -> RClass

Return Ruby’s Hash class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Hash", klass = ruby.class_hash());
    Ok(())
}
source

pub fn class_io(&self) -> RClass

Return Ruby’s IO class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == IO", klass = ruby.class_io());
    Ok(())
}
source

pub fn class_integer(&self) -> RClass

Return Ruby’s Integer class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Integer", klass = ruby.class_integer());
    Ok(())
}
source

pub fn class_match(&self) -> RClass

Return Ruby’s MatchData class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == MatchData", klass = ruby.class_match());
    Ok(())
}
source

pub fn class_method(&self) -> RClass

Return Ruby’s Method class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Method", klass = ruby.class_method());
    Ok(())
}
source

pub fn class_module(&self) -> RClass

Return Ruby’s Module class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Module", klass = ruby.class_module());
    Ok(())
}
source

pub fn class_name_error_mesg(&self) -> RClass

Return Ruby’s NameError::message class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        r#"klass.name == "NameError::message""#,
        klass = ruby.class_name_error_mesg()
    );
    Ok(())
}
source

pub fn class_nil_class(&self) -> RClass

Return Ruby’s NilClass class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == NilClass", klass = ruby.class_nil_class());
    Ok(())
}
source

pub fn class_numeric(&self) -> RClass

Return Ruby’s Numeric class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Numeric", klass = ruby.class_numeric());
    Ok(())
}
source

pub fn class_object(&self) -> RClass

Return Ruby’s Object class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Object", klass = ruby.class_object());
    Ok(())
}
source

pub fn class_proc(&self) -> RClass

Return Ruby’s Proc class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Proc", klass = ruby.class_proc());
    Ok(())
}
source

pub fn class_random(&self) -> RClass

Return Ruby’s Random class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Random", klass = ruby.class_random());
    Ok(())
}
source

pub fn class_range(&self) -> RClass

Return Ruby’s Range class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Range", klass = ruby.class_range());
    Ok(())
}
source

pub fn class_rational(&self) -> RClass

Return Ruby’s Rational class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Rational", klass = ruby.class_rational());
    Ok(())
}
source

pub fn class_refinement(&self) -> RClass

Available on ruby_gte_3_1 only.

Return Ruby’s Refinement class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Refinement", klass = ruby.class_refinement());
    Ok(())
}
source

pub fn class_regexp(&self) -> RClass

Return Ruby’s Regexp class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Regexp", klass = ruby.class_regexp());
    Ok(())
}
source

pub fn class_stat(&self) -> RClass

Return Ruby’s File::Stat class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == File::Stat", klass = ruby.class_stat());
    Ok(())
}
source

pub fn class_string(&self) -> RClass

Return Ruby’s String class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == String", klass = ruby.class_string());
    Ok(())
}
source

pub fn class_struct(&self) -> RClass

Return Ruby’s Struct class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Struct", klass = ruby.class_struct());
    Ok(())
}
source

pub fn class_symbol(&self) -> RClass

Return Ruby’s Symbol class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Symbol", klass = ruby.class_symbol());
    Ok(())
}
source

pub fn class_thread(&self) -> RClass

Return Ruby’s Thread class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Thread", klass = ruby.class_thread());
    Ok(())
}
source

pub fn class_time(&self) -> RClass

Return Ruby’s Time class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == Time", klass = ruby.class_time());
    Ok(())
}
source

pub fn class_true_class(&self) -> RClass

Return Ruby’s TrueClass class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == TrueClass", klass = ruby.class_true_class());
    Ok(())
}
source

pub fn class_unbound_method(&self) -> RClass

Return Ruby’s UnboundMethod class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == UnboundMethod",
        klass = ruby.class_unbound_method()
    );
    Ok(())
}
source§

impl Ruby

§Embedding

Functions relevant when embedding Ruby in Rust.

See also the embed module.

source

pub fn init(func: fn(_: &Ruby) -> Result<(), Error>) -> Result<(), String>

Available on crate feature embed only.

Initialises the Ruby VM.

See also init and setup.

Calling this function is only required when embedding Ruby in Rust. It is not required when embedding Rust in Ruby, e.g. in a Ruby Gem.

The Ruby VM can only be initialised once per process, and the Ruby VM cleanup will be run once the passed function has completed.

§Safety

This function takes a function pointer, rather than a closure, so that it is hard to leak Ruby values that could be used after the Ruby VM has finished. It is still possible to leak Ruby values with, for example, a static with interior mutability. Do not do this.

§Panics

Panics if this, init, or setup are collectively called more than once.

§Examples
magnus::Ruby::init(|ruby| {
    let result: i64 = ruby.eval("2 + 2")?;
    assert_eq!(result, 4);
    Ok(())
})
.unwrap()
source

pub fn script<T>(&self, name: T)
where T: IntoRString,

Available on crate feature embed only.

Sets the current script name.

source§

impl Ruby

§Encoding

Functions to access pre-defined Encodings.

See also the Encoding type.

source

pub fn enc_default_external(&self) -> Encoding

Returns the default internal encoding as a Ruby object.

This is the encoding used for anything out-of-process, such as reading from files or sockets.

source

pub fn enc_default_internal(&self) -> Option<Encoding>

Returns the default external encoding as a Ruby object.

If set, any out-of-process data is transcoded from the default external encoding to the default internal encoding.

source§

impl Ruby

§RbEncoding

Functions to access pre-defined encodings.

See also the RbEncoding type.

source

pub fn ascii8bit_encoding(&self) -> RbEncoding

Returns the encoding that represents ASCII-8BIT a.k.a. binary.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert_eq!(ruby.ascii8bit_encoding().name(), "ASCII-8BIT");
    Ok(())
}
source

pub fn utf8_encoding(&self) -> RbEncoding

Returns the encoding that represents UTF-8.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert_eq!(ruby.utf8_encoding().name(), "UTF-8");
    Ok(())
}
source

pub fn usascii_encoding(&self) -> RbEncoding

Returns the encoding that represents US-ASCII.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert_eq!(ruby.usascii_encoding().name(), "US-ASCII");
    Ok(())
}
source

pub fn locale_encoding(&self) -> RbEncoding

Returns the encoding that represents the process’ current locale.

This is dynamic. If you change the process’ locale that should also change the return value of this function.

source

pub fn filesystem_encoding(&self) -> RbEncoding

Returns the filesystem encoding.

This is the encoding that Ruby expects data from the OS’ file system to be encoded as, such as directory names.

source

pub fn default_external_encoding(&self) -> RbEncoding

Returns the default external encoding.

This is the encoding used for anything out-of-process, such as reading from files or sockets.

source

pub fn default_internal_encoding(&self) -> Option<RbEncoding>

Returns the default internal encoding.

If set, any out-of-process data is transcoded from the default external encoding to the default internal encoding.

source

pub fn find_encoding(&self, name: &str) -> Option<RbEncoding>

Returns the encoding with the name or alias name.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert_eq!(ruby.find_encoding("BINARY").unwrap().name(), "ASCII-8BIT");
    assert_eq!(ruby.find_encoding("UTF-8").unwrap().name(), "UTF-8");
    Ok(())
}
source§

impl Ruby

§Encoding Index

Functions to access pre-defined encodings.

See also the encoding::Index type.

source

pub fn ascii8bit_encindex(&self) -> Index

Returns the index for ASCII-8BIT a.k.a. binary.

source

pub fn utf8_encindex(&self) -> Index

Returns the index for UTF-8.

source

pub fn usascii_encindex(&self) -> Index

Returns the index for US-ASCII.

source

pub fn locale_encindex(&self) -> Index

Returns the index for the process’ current locale encoding.

This is dynamic. If you change the process’ locale that should also change the return value of this function.

source

pub fn filesystem_encindex(&self) -> Index

Returns the index for filesystem encoding.

This is the encoding that Ruby expects data from the OS’ file system to be encoded as, such as directory names.

source

pub fn find_encindex(&self, name: &str) -> Result<Index, Error>

Returns the index for the encoding with the name or alias name.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.find_encindex("UTF-8").is_ok());
    assert!(ruby.find_encindex("BINARY").is_ok());
    assert!(ruby.find_encindex("none").is_err());
    Ok(())
}
source§

impl Ruby

§Errors

Functions for working with errors and flow control encoded as an Error.

See also Error and the error module.

source

pub fn iter_break_value<T>(&self, val: T) -> Error
where T: IntoValue,

Create a new error that will break from a loop when returned to Ruby.

§Examples
use magnus::{prelude::*, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let i: i64 = ruby
        .range_new(1, 100, false)?
        .block_call("each", (), |args, _block| {
            let i = i64::try_convert(*args.get(0).unwrap())?;
            if i % 3 == 0 && i % 5 == 0 {
                // `block_call` takes a function pointer, not a
                // closure, so can't capture `ruby`. As we know this
                // will always be called from Ruby it's safe to get
                // `Ruby` without the checks that we're on a Ruby
                // thread.
                let ruby = unsafe { Ruby::get_unchecked() };
                Err(ruby.iter_break_value(i))
            } else {
                Ok(())
            }
        })?;

    assert_eq!(i, 15);
    Ok(())
}
source

pub fn warning(&self, s: &str)

Outputs s to Ruby’s stderr if Ruby is configured to output warnings.

source§

impl Ruby

§Core Exceptions

Functions to access Ruby’s built-in exception classes.

See also the exception module.

source

pub fn exception_arg_error(&self) -> ExceptionClass

Return Ruby’s ArgumentError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == ArgumentError",
        klass = ruby.exception_arg_error()
    );
    Ok(())
}
source

pub fn exception_eof_error(&self) -> ExceptionClass

Return Ruby’s EOFError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == EOFError",
        klass = ruby.exception_eof_error()
    );
    Ok(())
}
source

pub fn exception_enc_compat_error(&self) -> ExceptionClass

Return Ruby’s Encoding::CompatibilityError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == Encoding::CompatibilityError",
        klass = ruby.exception_enc_compat_error()
    );
    Ok(())
}
source

pub fn exception_encoding_error(&self) -> ExceptionClass

Return Ruby’s EncodingError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == EncodingError",
        klass = ruby.exception_encoding_error()
    );
    Ok(())
}
source

pub fn exception_exception(&self) -> ExceptionClass

Return Ruby’s Exception class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == Exception",
        klass = ruby.exception_exception()
    );
    Ok(())
}
source

pub fn exception_fatal(&self) -> ExceptionClass

Return Ruby’s fatal class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        r#"klass.name == "fatal""#,
        klass = ruby.exception_fatal()
    );
    Ok(())
}
source

pub fn exception_float_domain_error(&self) -> ExceptionClass

Return Ruby’s FloatDomainError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == FloatDomainError",
        klass = ruby.exception_float_domain_error()
    );
    Ok(())
}
source

pub fn exception_frozen_error(&self) -> ExceptionClass

Return Ruby’s FrozenError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == FrozenError",
        klass = ruby.exception_frozen_error()
    );
    Ok(())
}
source

pub fn exception_io_error(&self) -> ExceptionClass

Return Ruby’s IOError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "klass == IOError", klass = ruby.exception_io_error());
    Ok(())
}
source

pub fn exception_index_error(&self) -> ExceptionClass

Return Ruby’s IndexError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == IndexError",
        klass = ruby.exception_index_error()
    );
    Ok(())
}
source

pub fn exception_interrupt(&self) -> ExceptionClass

Return Ruby’s Interrupt class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == Interrupt",
        klass = ruby.exception_interrupt()
    );
    Ok(())
}
source

pub fn exception_key_error(&self) -> ExceptionClass

Return Ruby’s KeyError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == KeyError",
        klass = ruby.exception_key_error()
    );
    Ok(())
}
source

pub fn exception_load_error(&self) -> ExceptionClass

Return Ruby’s LoadError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == LoadError",
        klass = ruby.exception_load_error()
    );
    Ok(())
}
source

pub fn exception_local_jump_error(&self) -> ExceptionClass

Return Ruby’s LocalJumpError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == LocalJumpError",
        klass = ruby.exception_local_jump_error()
    );
    Ok(())
}
source

pub fn exception_math_domain_error(&self) -> ExceptionClass

Return Ruby’s Math::DomainError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == Math::DomainError",
        klass = ruby.exception_math_domain_error()
    );
    Ok(())
}
source

pub fn exception_name_error(&self) -> ExceptionClass

Return Ruby’s NameError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NameError",
        klass = ruby.exception_name_error()
    );
    Ok(())
}
source

pub fn exception_no_matching_pattern_error(&self) -> ExceptionClass

Available on ruby_gte_2_7 only.

Return Ruby’s NoMatchingPatternError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NoMatchingPatternError",
        klass = ruby.exception_no_matching_pattern_error()
    );
    Ok(())
}
source

pub fn exception_no_matching_pattern_key_error(&self) -> ExceptionClass

Available on ruby_gte_3_1 only.

Return Ruby’s NoMatchingPatternKeyError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NoMatchingPatternKeyError",
        klass = ruby.exception_no_matching_pattern_key_error()
    );
    Ok(())
}
source

pub fn exception_no_mem_error(&self) -> ExceptionClass

Return Ruby’s NoMemoryError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NoMemoryError",
        klass = ruby.exception_no_mem_error()
    );
    Ok(())
}
source

pub fn exception_no_method_error(&self) -> ExceptionClass

Return Ruby’s NoMethodError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NoMethodError",
        klass = ruby.exception_no_method_error()
    );
    Ok(())
}
source

pub fn exception_not_imp_error(&self) -> ExceptionClass

Return Ruby’s NotImplementedError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == NotImplementedError",
        klass = ruby.exception_not_imp_error()
    );
    Ok(())
}
source

pub fn exception_range_error(&self) -> ExceptionClass

Return Ruby’s RangeError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == RangeError",
        klass = ruby.exception_range_error()
    );
    Ok(())
}
source

pub fn exception_regexp_error(&self) -> ExceptionClass

Return Ruby’s RegexpError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == RegexpError",
        klass = ruby.exception_regexp_error()
    );
    Ok(())
}
source

pub fn exception_runtime_error(&self) -> ExceptionClass

Return Ruby’s RuntimeError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == RuntimeError",
        klass = ruby.exception_runtime_error()
    );
    Ok(())
}
source

pub fn exception_script_error(&self) -> ExceptionClass

Return Ruby’s ScriptError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == ScriptError",
        klass = ruby.exception_script_error()
    );
    Ok(())
}
source

pub fn exception_security_error(&self) -> ExceptionClass

Return Ruby’s SecurityError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SecurityError",
        klass = ruby.exception_security_error()
    );
    Ok(())
}
source

pub fn exception_signal(&self) -> ExceptionClass

Return Ruby’s SignalException class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SignalException",
        klass = ruby.exception_signal()
    );
    Ok(())
}
source

pub fn exception_standard_error(&self) -> ExceptionClass

Return Ruby’s StandardError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == StandardError",
        klass = ruby.exception_standard_error()
    );
    Ok(())
}
source

pub fn exception_stop_iteration(&self) -> ExceptionClass

Return Ruby’s StopIteration class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == StopIteration",
        klass = ruby.exception_stop_iteration()
    );
    Ok(())
}
source

pub fn exception_syntax_error(&self) -> ExceptionClass

Return Ruby’s SyntaxError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SyntaxError",
        klass = ruby.exception_syntax_error()
    );
    Ok(())
}
source

pub fn exception_sys_stack_error(&self) -> ExceptionClass

Return Ruby’s SystemStackError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SystemStackError",
        klass = ruby.exception_sys_stack_error()
    );
    Ok(())
}
source

pub fn exception_system_call_error(&self) -> ExceptionClass

Return Ruby’s SystemCallError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SystemCallError",
        klass = ruby.exception_system_call_error()
    );
    Ok(())
}
source

pub fn exception_system_exit(&self) -> ExceptionClass

Return Ruby’s SystemExit class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == SystemExit",
        klass = ruby.exception_system_exit()
    );
    Ok(())
}
source

pub fn exception_thread_error(&self) -> ExceptionClass

Return Ruby’s ThreadError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == ThreadError",
        klass = ruby.exception_thread_error()
    );
    Ok(())
}
source

pub fn exception_type_error(&self) -> ExceptionClass

Return Ruby’s TypeError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == TypeError",
        klass = ruby.exception_type_error()
    );
    Ok(())
}
source

pub fn exception_zero_div_error(&self) -> ExceptionClass

Return Ruby’s ZeroDivisionError class.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "klass == ZeroDivisionError",
        klass = ruby.exception_zero_div_error()
    );
    Ok(())
}
source§

impl Ruby

§Float

Functions that can be used to create instances of Float.

See also the Float type.

source

pub fn float_from_f64(&self, n: f64) -> Float

Create a new Float from an f64.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let f = ruby.float_from_f64(1.7272337110188893e-77);
    rb_assert!(ruby, "f == 1.7272337110188893e-77", f);

    let f = ruby.float_from_f64(1.7272337110188890e-77);
    rb_assert!(ruby, "f == 1.7272337110188890e-77", f);

    Ok(())
}
source§

impl Ruby

§GC

Functions for working with Ruby’s Garbage Collector.

See also the gc module.

source

pub fn gc_disable(&self) -> bool

Disable automatic GC runs.

This could result in other Ruby api functions unexpectedly raising NoMemError.

Returns true if GC was already disabled, false otherwise.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let was_disabled = ruby.gc_disable();

    // GC is off

    // return GC to previous state
    if !was_disabled {
        ruby.gc_enable();
    }

    Ok(())
}
source

pub fn gc_enable(&self) -> bool

Enable automatic GC run.

Garbage Collection is enabled by default, calling this function only makes sense if disable was previously called.

Returns true if GC was previously disabled, false otherwise.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let was_disabled = ruby.gc_enable();

    // GC is on

    // return GC to previous state
    if was_disabled {
        ruby.gc_disable();
    }

    Ok(())
}
source

pub fn gc_start(&self)

Trigger a “full” GC run.

This will perform a full mark phase and a complete sweep phase, but may not run every single proceess associated with garbage collection.

Finalisers will be deferred to run later.

Currently (with versions of Ruby that support compaction) it will not trigger compaction.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.gc_start();

    Ok(())
}
source

pub fn gc_adjust_memory_usage(&self, diff: isize)

Inform Ruby of external memory usage.

The Ruby GC is run when Ruby thinks it’s running out of memory, but won’t take into account any memory allocated outside of Ruby api functions. This function can be used to give Ruby a more accurate idea of how much memory the process is using.

Pass negative numbers to indicate memory has been freed.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let buf = Vec::<u8>::with_capacity(1024 * 1024);
    let mem_size = buf.capacity() * std::mem::size_of::<u8>();
    ruby.gc_adjust_memory_usage(mem_size as isize);

    // ...

    drop(buf);
    ruby.gc_adjust_memory_usage(-(mem_size as isize));

    Ok(())
}
source

pub fn gc_count(&self) -> usize

Returns the number of garbage collections that have been run since the start of the process.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let before = ruby.gc_count();
    ruby.gc_start();
    assert!(ruby.gc_count() > before);

    Ok(())
}
source

pub fn gc_stat<T>(&self, key: T) -> Result<usize, Error>
where T: IntoSymbol,

Returns the GC profiling value for key.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.gc_stat("heap_live_slots")? > 1);

    Ok(())
}
source

pub fn gc_all_stats(&self) -> RHash

Returns all possible key/value pairs for stat as a Ruby Hash.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let stats = ruby.gc_all_stats();
    let live_slots: usize = stats.fetch(ruby.to_symbol("heap_live_slots"))?;
    assert!(live_slots > 1);

    Ok(())
}
source§

impl Ruby

§Integer

Functions that can be used to create instances of Integer.

See also the Integer type.

source

pub fn integer_from_i64(&self, n: i64) -> Integer

Create a new Integer from an i64.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "i == 0", i = ruby.integer_from_i64(0));
    rb_assert!(
        ruby,
        "i == 4611686018427387904",
        i = ruby.integer_from_i64(4611686018427387904),
    );
    rb_assert!(
        ruby,
        "i == -4611686018427387905",
        i = ruby.integer_from_i64(-4611686018427387905),
    );

    Ok(())
}
source

pub fn integer_from_u64(&self, n: u64) -> Integer

Create a new Integer from a u64.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!("i == 0", i = ruby.integer_from_u64(0));
    rb_assert!(
        "i == 4611686018427387904",
        i = ruby.integer_from_u64(4611686018427387904),
    );

    Ok(())
}
source§

impl Ruby

§Conversion to Value

Helpers for the IntoValue trait.

See also the IntoValue trait.

source

pub fn into_value<T>(&self, val: T) -> Value
where T: IntoValue,

Convert val into Value.

source§

impl Ruby

§RModule

Functions that can be used to create Ruby modules.

See also the RModule type.

source

pub fn module_new(&self) -> RModule

Create a new anonymous module.

§Examples
use magnus::{prelude::*, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let module = ruby.module_new();
    assert!(module.is_kind_of(ruby.class_module()));

    Ok(())
}
source§

impl Ruby

§Core Modules

Functions to access Ruby’s built-in modules.

See also Ruby::define_module and the module module.

source

pub fn module_comparable(&self) -> RModule

Return Ruby’s Comparable module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Comparable", md = ruby.module_comparable());

    Ok(())
}
source

pub fn module_enumerable(&self) -> RModule

Return Ruby’s Enumerable module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Enumerable", md = ruby.module_enumerable());

    Ok(())
}
source

pub fn module_errno(&self) -> RModule

Return Ruby’s Errno module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Errno", md = ruby.module_errno());

    Ok(())
}
source

pub fn module_file_test(&self) -> RModule

Return Ruby’s FileTest module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == FileTest", md = ruby.module_file_test());

    Ok(())
}
source

pub fn module_gc(&self) -> RModule

Return Ruby’s GC module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == GC", md = ruby.module_gc());

    Ok(())
}
source

pub fn module_kernel(&self) -> RModule

Return Ruby’s Kernel module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Kernel", md = ruby.module_kernel());

    Ok(())
}
source

pub fn module_math(&self) -> RModule

Return Ruby’s Math module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Math", md = ruby.module_math());

    Ok(())
}
source

pub fn module_process(&self) -> RModule

Return Ruby’s Process module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "md == Process", md = ruby.module_process());

    Ok(())
}
source

pub fn module_wait_readable(&self) -> RModule

Return Ruby’s IO::WaitReadable module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "md == IO::WaitReadable",
        md = ruby.module_wait_readable()
    );

    Ok(())
}
source

pub fn module_wait_writable(&self) -> RModule

Return Ruby’s IO::WaitWritable module.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(
        ruby,
        "md == IO::WaitWritable",
        md = ruby.module_wait_writable()
    );

    Ok(())
}
source§

impl Ruby

§RArray

Functions that can be used to create Ruby Arrays.

See also the RArray type.

source

pub fn ary_new(&self) -> RArray

Create a new empty RArray.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_new();
    assert!(ary.is_empty());

    Ok(())
}
source

pub fn ary_new_capa(&self, n: usize) -> RArray

Create a new empty RArray with capacity for n elements pre-allocated.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_new_capa(16);
    assert!(ary.is_empty());

    Ok(())
}
source

pub fn ary_from_vec<T>(&self, vec: Vec<T>) -> RArray

Create a new RArray from a Rust vector.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_from_vec(vec![1, 2, 3]);
    rb_assert!(ruby, "ary == [1, 2, 3]", ary);

    Ok(())
}
source

pub fn ary_new_from_values<T>(&self, slice: &[T]) -> RArray
where T: ReprValue,

Create a new RArray containing the elements in slice.

§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_new_from_values(&[
        ruby.to_symbol("a").as_value(),
        ruby.integer_from_i64(1).as_value(),
        ruby.qnil().as_value(),
    ]);
    rb_assert!(ruby, "ary == [:a, 1, nil]", ary);

    Ok(())
}
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_new_from_values(&[
        ruby.to_symbol("a"),
        ruby.to_symbol("b"),
        ruby.to_symbol("c"),
    ]);
    rb_assert!(ruby, "ary == [:a, :b, :c]", ary);

    Ok(())
}
source

pub fn ary_from_iter<I, T>(&self, iter: I) -> RArray
where I: IntoIterator<Item = T>, T: IntoValue,

Create a new RArray from a Rust iterator.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.ary_from_iter((1..4).map(|i| i * 10));
    rb_assert!(ruby, "ary == [10, 20, 30]", ary);

    Ok(())
}
source§

impl Ruby

§RBignum

Functions that can be used to create instances of Ruby’s large interger representation.

See also the RBignum type.

source

pub fn bignum_from_i64(&self, n: i64) -> Result<RBignum, Fixnum>

Create a new RBignum from an i64.

Returns Ok(RBignum) if n is large enough to require a bignum, otherwise returns Err(Fixnum).

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.bignum_from_i64(4611686018427387904).is_ok());
    assert!(ruby.bignum_from_i64(-4611686018427387905).is_ok());
    // too small
    assert!(ruby.bignum_from_i64(0).is_err());

    Ok(())
}
source

pub fn bignum_from_u64(&self, n: u64) -> Result<RBignum, Fixnum>

Create a new RBignum from an u64.

Returns Ok(RBignum) if n is large enough to require a bignum, otherwise returns Err(Fixnum).

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.bignum_from_u64(4611686018427387904).is_ok());
    // too small
    assert!(ruby.bignum_from_u64(0).is_err());

    Ok(())
}
source§

impl Ruby

§RFloat

Functions that can be used to create Ruby Floats.

See also the RFloat type.

source

pub fn r_float_from_f64(&self, n: f64) -> Result<RFloat, Flonum>

Create a new RFloat from an f64.

Returns Ok(RFloat) if n requires a high precision float, otherwise returns Err(Flonum).

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let f = ruby.r_float_from_f64(1.7272337110188890e-77).unwrap();
    rb_assert!(ruby, "f == 1.7272337110188890e-77", f);

    // can fit within a Flonum, so does not require an RFloat
    assert!(ruby.r_float_from_f64(1.7272337110188893e-77).is_err());

    Ok(())
}
source§

impl Ruby

§RHash

Functions that can be used to create Ruby Hashes.

See also the RHash type.

source

pub fn hash_new(&self) -> RHash

Create a new empty RHash.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let hash = ruby.hash_new();
    assert!(hash.is_empty());

    Ok(())
}
source

pub fn hash_new_capa(&self, n: usize) -> RHash

Available on ruby_gte_3_2 only.

Create a new empty RHash with capacity for n elements pre-allocated.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let ary = ruby.hash_new_capa(16);
    assert!(ary.is_empty());

    Ok(())
}
source§

impl Ruby

§RRational

Functions that can be used to create Ruby Rationals.

See also the RRational type.

source

pub fn rational_new(&self, num: i64, den: NonZeroI64) -> RRational

Create a new RRational.

§Examples
use std::num::NonZeroI64;

use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let rational = ruby.rational_new(2, NonZeroI64::new(4).unwrap());
    assert_eq!(rational.to_string(), "1/2");

    Ok(())
}
source§

impl Ruby

§RRegexp

Functions that can be used to create Ruby Regexps.

See also the RRegexp type.

source

pub fn reg_new(&self, pattern: &str, opts: Opts) -> Result<RRegexp, Error>

Create a new Regexp from the Rust string pattern.

The encoding of the Ruby regexp will be UTF-8.

§Examples
use magnus::{r_regexp::Opts, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let regexp = ruby.reg_new("foo", Opts::new().ignorecase())?;
    rb_assert!(ruby, r#"regexp == /foo/i"#, regexp);

    Ok(())
}
source§

impl Ruby

§RString

Functions that can be used to create Ruby Strings.

See also the RString type.

source

pub fn str_new(&self, s: &str) -> RString

Create a new Ruby string from the Rust string s.

The encoding of the Ruby string will be UTF-8.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let val = ruby.str_new("example");
    rb_assert!(ruby, r#"val == "example""#, val);

    Ok(())
}
source

pub fn str_buf_new(&self, n: usize) -> RString

Create a new Ruby string with capacity n.

The encoding will be set to ASCII-8BIT (aka BINARY). See also with_capacity.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let buf = ruby.str_buf_new(4096);
    buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
    rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);

    Ok(())
}
source

pub fn str_with_capacity(&self, n: usize) -> RString

Create a new Ruby string with capacity n.

The encoding will be set to UTF-8. See also buf_new.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let s = ruby.str_with_capacity(9);
    s.cat("foo");
    s.cat("bar");
    s.cat("baz");
    rb_assert!(ruby, r#"s == "foobarbaz""#, s);

    Ok(())
}
source

pub fn str_from_slice(&self, s: &[u8]) -> RString

Create a new Ruby string from the Rust slice s.

The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let buf = ruby.str_from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
    rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);

    Ok(())
}
source

pub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString
where T: AsRef<[u8]>, E: Into<RbEncoding>,

Create a new Ruby string from the value s with the encoding enc.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let val = ruby.enc_str_new("example", ruby.usascii_encoding());
    rb_assert!(ruby, r#"val == "example""#, val);

    Ok(())
}
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let val = ruby.enc_str_new([255, 128, 128], ruby.ascii8bit_encoding());
    rb_assert!(
        ruby,
        r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#,
        val
    );

    Ok(())
}
source

pub fn str_from_char(&self, c: char) -> RString

Create a new Ruby string from the Rust char c.

The encoding of the Ruby string will be UTF-8.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let c = ruby.str_from_char('a');
    rb_assert!(ruby, r#"c == "a""#, c);

    Ok(())
}
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let c = ruby.str_from_char('🦀');
    rb_assert!(ruby, r#"c == "🦀""#, c);

    Ok(())
}
source

pub fn chr<T>(&self, code: u32, enc: T) -> Result<RString, Error>
where T: Into<RbEncoding>,

Create a new Ruby string containing the codepoint code in the encoding enc.

The encoding of the Ruby string will be the passed encoding enc.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let c = ruby.chr(97, ruby.usascii_encoding())?;
    rb_assert!(ruby, r#"c == "a""#, c);

    Ok(())
}
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let c = ruby.chr(129408, ruby.utf8_encoding())?;
    rb_assert!(ruby, r#"c == "🦀""#, c);

    Ok(())
}
source§

impl Ruby

§Struct

Functions that can be used to create Ruby Struct classes.

See also the struct module.

source

pub fn define_struct<T>( &self, name: Option<&str>, members: T ) -> Result<RClass, Error>
where T: StructMembers,

Define a Ruby Struct class.

members is a tuple of &str, of between lengths 1 to 12 inclusive.

§Examples

When providing None for the name the struct class’s name will be taken from the first constant it is assigned to:

use magnus::{prelude::*, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let struct_class = ruby.define_struct(None, ("foo", "bar"))?;
    ruby.define_global_const("Example", struct_class)?;

    assert_eq!(unsafe { struct_class.name().to_owned() }, "Example");

    let instance = struct_class.new_instance((1, 2))?;
    assert_eq!(instance.inspect(), "#<struct Example foo=1, bar=2>");

    Ok(())
}

When providing Some("Name") for the name the struct will be defined under Struct:

use magnus::{prelude::*, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let struct_class = ruby.define_struct(Some("Example"), ("foo", "bar"))?;

    assert_eq!(unsafe { struct_class.name().to_owned() }, "Struct::Example");

    let instance = struct_class.new_instance((1, 2))?;
    assert_eq!(instance.inspect(), "#<struct Struct::Example foo=1, bar=2>");

    Ok(())
}
source§

impl Ruby

§RTypedData

Functions to wrap Rust data in a Ruby object.

See also typed_data::Obj and the RTypedData type.

source

pub fn wrap<T>(&self, data: T) -> RTypedData
where T: TypedData,

Wrap the Rust type T in a Ruby object.

§Examples
use magnus::{prelude::*, Error, Ruby};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;

    let value = ruby.wrap(Point { x: 4, y: 2 });
    assert!(value.is_kind_of(point_class));

    Ok(())
}
source

pub fn wrap_as<T>(&self, data: T, class: RClass) -> RTypedData
where T: TypedData,

Wrap the Rust type T in a Ruby object that is an instance of the given class.

See also TypedData::class_for.

§Panics

Panics if class is not a subclass of <T as TypedData>::class().

§Examples
use magnus::{prelude::*, Error, Ruby};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;
    let point_sub_class = ruby.define_class("SubPoint", point_class)?;

    let value = ruby.wrap_as(Point { x: 4, y: 2 }, point_sub_class);
    assert!(value.is_kind_of(point_sub_class));
    assert!(value.is_kind_of(point_class));

    Ok(())
}

Allowing a wrapped type to be subclassed from Ruby:

(note, in this example Point does not have and does not call the initialize method, subclasses would need to override the class new method rather than initialize)

use magnus::{function, method, prelude::*, Error, RClass, RTypedData, Ruby, Value};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

impl Point {
    fn new(ruby: &Ruby, class: RClass, x: isize, y: isize) -> RTypedData {
        ruby.wrap_as(Self { x, y }, class)
    }
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;
    point_class.define_singleton_method("new", method!(Point::new, 2))?;
    point_class
        .define_singleton_method("inherited", function!(RClass::undef_default_alloc_func, 1))?;

    let value: Value = ruby.eval(
        r#"
          class SubPoint < Point
          end
          SubPoint.new(4, 2)
        "#,
    )?;

    assert!(value.is_kind_of(ruby.class_object().const_get::<_, RClass>("SubPoint")?));
    assert!(value.is_kind_of(point_class));

    Ok(())
}
source§

impl Ruby

§Range

Functions that can be used to create Ruby Ranges.

See also the Range type.

source

pub fn range_new<T, U>( &self, beg: T, end: U, excl: bool ) -> Result<Range, Error>
where T: IntoValue, U: IntoValue,

Create a new Range.

Returns Err if beg and end are not comparable.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let range = ruby.range_new(2, 7, false)?;
    rb_assert!(ruby, "range == (2..7)", range);

    Ok(())
}
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let range = ruby.range_new(2, 7, true)?;
    rb_assert!(ruby, "range == (2...7)", range);

    Ok(())
}
source§

impl Ruby

§Argument Parsing

Functions for handling argument parsing.

See also the scan_args module.

source

pub fn check_arity<T>(&self, len: usize, bounds: T) -> Result<(), Error>
where T: RangeBounds<usize>,

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

§Examples
use magnus::{function, Error, RString, Ruby, Value};

fn test(ruby: &Ruby, args: &[Value]) -> Result<RString, Error> {
    ruby.check_arity(args.len(), 2..5)?;
    ruby.ary_new_from_values(args).join(", ")
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function("test", function!(test, -1));

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

    Ok(())
}
source§

impl Ruby

§Symbol

Functions that can be used to create Ruby Symbols.

See also the Symbol type.

source

pub fn to_symbol<T: AsRef<str>>(&self, name: T) -> Symbol

Create a new Symbol from name.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let sym = ruby.to_symbol("example");
    rb_assert!(ruby, ":example == sym", sym);

    Ok(())
}
source§

impl Ruby

§typed_data::Obj

Functions to wrap Rust data in a Ruby object.

See also RTypedData and the typed_data::Obj type.

source

pub fn obj_wrap<T>(&self, data: T) -> Obj<T>
where T: TypedData,

Wrap the Rust type T in a Ruby object.

§Examples
use magnus::{prelude::*, Error, Ruby};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;

    let value = ruby.obj_wrap(Point { x: 4, y: 2 });
    assert!(value.is_kind_of(point_class));

    Ok(())
}
source

pub fn obj_wrap_as<T>(&self, data: T, class: RClass) -> Obj<T>
where T: TypedData,

Wrap the Rust type T in a Ruby object that is an instance of the given class.

See also TypedData::class_for.

§Panics

Panics if class is not a subclass of <T as TypedData>::class().

§Examples
use magnus::{prelude::*, Error, Ruby};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;
    let point_sub_class = ruby.define_class("SubPoint", point_class)?;

    let value = ruby.obj_wrap_as(Point { x: 4, y: 2 }, point_sub_class);
    assert!(value.is_kind_of(point_sub_class));
    assert!(value.is_kind_of(point_class));

    Ok(())
}

Allowing a wrapped type to be subclassed from Ruby:

(note, in this example Point does not have and does not call the initialize method, subclasses would need to override the class new method rather than initialize)

use magnus::{function, method, prelude::*, typed_data, Error, RClass, Ruby, Value};

#[magnus::wrap(class = "Point")]
struct Point {
    x: isize,
    y: isize,
}

impl Point {
    fn new(ruby: &Ruby, class: RClass, x: isize, y: isize) -> typed_data::Obj<Self> {
        ruby.obj_wrap_as(Self { x, y }, class)
    }
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    let point_class = ruby.define_class("Point", ruby.class_object())?;
    point_class.define_singleton_method("new", method!(Point::new, 2))?;
    point_class
        .define_singleton_method("inherited", function!(RClass::undef_default_alloc_func, 1))?;

    let value: Value = ruby.eval(
        r#"
          class SubPoint < Point
          end
          SubPoint.new(4, 2)
        "#,
    )?;

    assert!(value.is_kind_of(ruby.class_object().const_get::<_, RClass>("SubPoint")?));
    assert!(value.is_kind_of(point_class));

    Ok(())
}
source§

impl Ruby

§Flonum

Functions that can be used to create instances of Ruby’s lower precision floating point representation.

See also the Flonum type.

source

pub fn flonum_from_f64(&self, n: f64) -> Result<Flonum, RFloat>

Create a new Flonum from a f64.

Returns Ok(Flonum) if n can be represented as a Flonum, otherwise returns Err(RFloat).

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let f = ruby.flonum_from_f64(1.7272337110188893e-77).unwrap();
    rb_assert!(ruby, "f == 1.7272337110188893e-77", f);

    // representable as a Float, but Flonum does not have enough precision
    assert!(ruby.flonum_from_f64(1.7272337110188890e-77).is_err());

    Ok(())
}
source§

impl Ruby

§Extracting values from Opaque/Lazy

Magnus has a number of container types where it is only safe to access the inner Ruby value when you can provide a Ruby handle. The functions here provide a unified api to access those container types.

See also the Opaque and Lazy types.

source

pub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> T
where T: ReprValue,

Get the inner value from wrapper.

self acts as a token proving this is called from a Ruby thread and thus it is safe to return the inner value. See Opaque and Lazy.

§Examples
use magnus::{rb_assert, value::Opaque, Ruby};

let ruby = Ruby::get().unwrap();
let opaque_str = Opaque::from(ruby.str_new("example"));

// send to another Ruby thread

let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread
let str = ruby.get_inner(opaque_str);
rb_assert!(ruby, r#"str == "example""#, str);
use magnus::{rb_assert, value::Lazy, RString, Ruby};

static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));

let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised
let str = ruby.get_inner(&STATIC_STR);
rb_assert!(ruby, r#"str == "example""#, str);
source

pub fn get_inner_ref<'a, T>( &self, wrapper: &'a impl InnerRef<Value = T> ) -> &'a T
where T: ReprValue,

Get a reference to the inner value of wrapper.

self acts as a token proving this is called from a Ruby thread and thus it is safe to access the inner value. See Opaque and Lazy.

source§

impl Ruby

§false

Get Ruby’s false value.

See also the Qfalse type.

source

pub fn qfalse(&self) -> Qfalse

Returns Ruby’s false value.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "val == false", val = ruby.qfalse());

    Ok(())
}
source§

impl Ruby

§nil

Get Ruby’s nil value.

See also the Qnil type.

source

pub fn qnil(&self) -> Qnil

Returns Ruby’s nil value.

This should optimise to a constant reference.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "val == nil", val = ruby.qnil());

    Ok(())
}
source§

impl Ruby

§true

Get Ruby’s true value.

See also the Qtrue type.

source

pub fn qtrue(&self) -> Qtrue

Returns Ruby’s true value.

This should optimise to a constant reference.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    rb_assert!(ruby, "val == true", val = ruby.qtrue());

    Ok(())
}
source§

impl Ruby

§Fixnum

Functions that can be used to create instances of Ruby’s small/fast integer representation.

See also the Fixnum type.

source

pub fn fixnum_from_i64(&self, n: i64) -> Result<Fixnum, RBignum>

Create a new Fixnum from an i64.

Returns Ok(Fixnum) if n is in range for Fixnum, otherwise returns Err(RBignum).

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.fixnum_from_i64(0).is_ok());
    // too big
    assert!(ruby.fixnum_from_i64(4611686018427387904).is_err());
    assert!(ruby.fixnum_from_i64(-4611686018427387905).is_err());

    Ok(())
}
source

pub fn fixnum_from_u64(&self, n: u64) -> Result<Fixnum, RBignum>

Create a new Fixnum from a u64.

Returns Ok(Fixnum) if n is in range for Fixnum, otherwise returns Err(RBignum).

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.fixnum_from_u64(0).is_ok());
    // too big
    assert!(ruby.fixnum_from_u64(4611686018427387904).is_err());

    Ok(())
}
source§

impl Ruby

§StaticSymbol

Functions to create Ruby Symbols that will never be garbage collected.

See also the StaticSymbol type.

source

pub fn sym_new<T>(&self, name: T) -> StaticSymbol
where T: IntoId,

Create a new StaticSymbol.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let sym = ruby.sym_new("example");
    rb_assert!(ruby, ":example == sym", sym);

    Ok(())
}
source

pub fn check_symbol(&self, name: &str) -> Option<StaticSymbol>

Return the StaticSymbol for name, if one exists.

§Examples
use magnus::{Error, Ruby, StaticSymbol};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.check_symbol("example").is_none());
    let _: StaticSymbol = ruby.eval(":example")?;
    assert!(ruby.check_symbol("example").is_some());

    Ok(())
}
source§

impl Ruby

§Id

Functions to create Ruby’s low-level Symbol representation.

See also the Id type.

source

pub fn intern(&self, name: &str) -> Id

Create a new Id for name.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let id = ruby.intern("example");
    assert_eq!(id.name()?, "example");

    Ok(())
}
source

pub fn check_id(&self, name: &str) -> Option<Id>

Return the Id for name, if one exists.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.check_id("example").is_none());
    ruby.intern("example");
    assert!(ruby.check_id("example").is_some());

    Ok(())
}
source§

impl Ruby

§Globals

Functions for defining global variables, constants, etc, as well as accessing current Ruby execution status such as calling the current super method.

See also functions in the root module.

source

pub fn define_class( &self, name: &str, superclass: RClass ) -> Result<RClass, Error>

Define a class in the root scope.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_class("Example", ruby.class_object())?;
    rb_assert!(ruby, "Example.is_a?(Class)");

    Ok(())
}
source

pub fn define_module(&self, name: &str) -> Result<RModule, Error>

Define a module in the root scope.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_module("Example")?;
    rb_assert!(ruby, "Example.is_a?(Module)");
    rb_assert!(ruby, "!Example.is_a?(Class)");

    Ok(())
}
source

pub fn define_error( &self, name: &str, superclass: ExceptionClass ) -> Result<ExceptionClass, Error>

Define an exception class in the root scope.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_error("ExampleError", ruby.exception_standard_error())?;
    rb_assert!(ruby, "ExampleError.is_a?(Class)");
    rb_assert!(ruby, "ExampleError < Exception");

    Ok(())
}
source

pub fn define_variable<T>( &self, name: &str, initial: T ) -> Result<*mut Value, Error>
where T: IntoValue,

Define a global variable.

§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let v = ruby.define_variable("example", 42)?;
    rb_assert!(ruby, "$example == 42");

    // safe as long as another thread isn't modifying v
    unsafe {
        *v = ruby.str_new("answer").as_value();
    }
    rb_assert!(ruby, r#"$example == "answer""#);

    Ok(())
}
source

pub fn define_global_const<T>(&self, name: &str, value: T) -> Result<(), Error>
where T: IntoValue,

Define a global constant.

§Examples
use magnus::{rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_const("EXAMPLE", 42)?;
    rb_assert!(ruby, "EXAMPLE == 42");

    Ok(())
}
source

pub fn define_global_function<M>(&self, name: &str, func: M)
where M: Method,

Define a method in the root scope.

§Examples
use magnus::{function, rb_assert, Error, Ruby};

fn greet(subject: String) -> String {
    format!("Hello, {}!", subject)
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function("greet", function!(greet, 1));
    rb_assert!(ruby, r#"greet("world") == "Hello, world!""#);

    Ok(())
}
source

pub fn backref_get(&self) -> Option<RMatch>

Returns the result of the most recent regexp match.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let regexp = ruby.reg_new("b(.)r", Default::default())?;
    let result = regexp.reg_match("foo bar baz")?;
    assert_eq!(result, Some(4));

    let match_data = ruby.backref_get().unwrap();
    assert_eq!(match_data.matched().to_string()?, String::from("bar"));
    assert_eq!(
        match_data.nth_match(1).map(|v| v.to_string().unwrap()),
        Some(String::from("a"))
    );

    Ok(())
}
source

pub fn current_receiver<T>(&self) -> Result<T, Error>
where T: TryConvert,

Return the Ruby self of the current method context.

Returns Err if called outside a method context or the conversion fails.

§Examples
use magnus::{method, prelude::*, rb_assert, Error, Ruby, Value};

fn test(ruby: &Ruby, rb_self: Value) -> Result<bool, Error> {
    rb_self.equal(ruby.current_receiver::<Value>()?)
}

fn example(ruby: &Ruby) -> Result<(), Error> {
    ruby.define_global_function("test", method!(test, 0));

    rb_assert!(ruby, "test");

    Ok(())
}
source

pub fn call_super<A, T>(&self, args: A) -> Result<T, Error>
where A: ArgList, T: TryConvert,

Call the super method of the current method context.

Returns Ok(T) if the super method exists and returns without error, and the return value converts to a T, or returns Err if there is no super method, the super method raises or the conversion fails.

§Examples
use magnus::{function, prelude::*, rb_assert, Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    let a = ruby.eval(
        r#"
          class A
            def test
              "Hello from A"
            end
          end
          A
        "#,
    )?;

    let b = ruby.define_class("B", a)?;
    fn test(ruby: &Ruby) -> Result<String, Error> {
        let s: String = ruby.call_super(())?;
        Ok(format!("{}, and hello from B", s))
    }
    b.define_method("test", function!(test, 0))?;

    rb_assert!(ruby, r#"B.new.test == "Hello from A, and hello from B""#);

    Ok(())
}
source

pub fn require<T>(&self, feature: T) -> Result<bool, Error>
where T: IntoRString,

Finds and loads the given feature if not already loaded.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert!(ruby.require("net/http")?);

    Ok(())
}
source

pub fn eval<T>(&self, s: &str) -> Result<T, Error>
where T: TryConvert,

Evaluate a string of Ruby code, converting the result to a T.

Ruby will use the ‘ASCII-8BIT’ (aka binary) encoding for any Ruby string literals in the passed string of Ruby code. See the eval macro or Binding::eval for an alternative that supports utf-8.

Errors if s contains a null byte, the conversion fails, or on an uncaught Ruby exception.

§Examples
use magnus::{Error, Ruby};

fn example(ruby: &Ruby) -> Result<(), Error> {
    assert_eq!(ruby.eval::<i64>("1 + 2")?, 3);

    Ok(())
}

Auto Trait Implementations§

§

impl Freeze for Ruby

§

impl RefUnwindSafe for Ruby

§

impl !Send for Ruby

§

impl !Sync for Ruby

§

impl Unpin for Ruby

§

impl UnwindSafe for Ruby

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.