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.
- Accessing
Ruby
- how to get aRuby
handle - Argument Parsing - helpers for argument handling
- Blocks - working with Ruby blocks
- Conversion to
Value
- Core Classes - access built-in classes
- Core Exceptions - access built-in exceptions
- Core Modules - access built-in modules
- Embedding - functions relevant when embedding Ruby in Rust
Encoding
- string encoding- Encoding Index - string encoding
- Errors
- Extracting values from
Opaque
/Lazy
false
Fixnum
- small/fast integersFloat
Flonum
- lower precision/fast floatsGC
- Garbage Collection- Globals - global variables, etc, plus current VM state such
as calling the current
super
method. Id
- low-level Symbol representationInteger
nil
Proc
- Ruby’s blocks as objectsRange
RArray
RbEncoding
- string encodingRBignum
- big integersRFloat
RHash
RModule
RRational
RRegexp
RString
RTypedData
- wrapping Rust data in a Ruby objectStaticSymbol
- non GC’d symbolsStruct
Symbol
true
typed_data::Obj
- wrapping Rust data in a Ruby object
Implementations§
source§impl Ruby
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.
sourcepub fn get() -> Result<Self, RubyUnavailableError>
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)
.
sourcepub fn get_with<T>(value: T) -> Selfwhere
T: ReprValue,
pub fn get_with<T>(value: T) -> Selfwhere
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.
sourcepub unsafe fn get_unchecked() -> Self
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
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.
sourcepub fn proc_new<R>(&self, block: fn(_: &[Value], _: Option<Proc>) -> R) -> Procwhere
R: BlockReturn,
pub fn proc_new<R>(&self, block: fn(_: &[Value], _: Option<Proc>) -> R) -> Procwhere
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(())
}
sourcepub fn proc_from_fn<F, R>(&self, block: F) -> Proc
pub fn proc_from_fn<F, R>(&self, block: F) -> Proc
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
impl Ruby
sourcepub fn block_given(&self) -> bool
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(())
}
sourcepub fn block_proc(&self) -> Result<Proc, Error>
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(())
}
sourcepub fn yield_value<T, U>(&self, val: T) -> Result<U, Error>where
T: IntoValue,
U: TryConvert,
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(())
}
sourcepub fn yield_values<T, U>(&self, vals: T) -> Result<U, Error>where
T: ArgList,
U: TryConvert,
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(())
}
sourcepub fn yield_splat<T>(&self, vals: RArray) -> Result<T, Error>where
T: TryConvert,
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
impl Ruby
sourcepub fn class_array(&self) -> RClass
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(())
}
sourcepub fn class_basic_object(&self) -> RClass
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(())
}
sourcepub fn class_binding(&self) -> RClass
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(())
}
sourcepub fn class_class(&self) -> RClass
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(())
}
sourcepub fn class_complex(&self) -> RClass
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(())
}
sourcepub fn class_dir(&self) -> RClass
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(())
}
sourcepub fn class_encoding(&self) -> RClass
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(())
}
sourcepub fn class_enumerator(&self) -> RClass
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(())
}
sourcepub fn class_false_class(&self) -> RClass
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(())
}
sourcepub fn class_file(&self) -> RClass
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(())
}
sourcepub fn class_float(&self) -> RClass
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(())
}
sourcepub fn class_hash(&self) -> RClass
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(())
}
sourcepub fn class_io(&self) -> RClass
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(())
}
sourcepub fn class_integer(&self) -> RClass
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(())
}
sourcepub fn class_match(&self) -> RClass
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(())
}
sourcepub fn class_method(&self) -> RClass
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(())
}
sourcepub fn class_module(&self) -> RClass
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(())
}
sourcepub fn class_name_error_mesg(&self) -> RClass
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(())
}
sourcepub fn class_nil_class(&self) -> RClass
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(())
}
sourcepub fn class_numeric(&self) -> RClass
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(())
}
sourcepub fn class_object(&self) -> RClass
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(())
}
sourcepub fn class_proc(&self) -> RClass
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(())
}
sourcepub fn class_random(&self) -> RClass
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(())
}
sourcepub fn class_range(&self) -> RClass
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(())
}
sourcepub fn class_rational(&self) -> RClass
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(())
}
sourcepub fn class_refinement(&self) -> RClass
Available on ruby_gte_3_1
only.
pub fn class_refinement(&self) -> RClass
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(())
}
sourcepub fn class_regexp(&self) -> RClass
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(())
}
sourcepub fn class_stat(&self) -> RClass
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(())
}
sourcepub fn class_string(&self) -> RClass
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(())
}
sourcepub fn class_struct(&self) -> RClass
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(())
}
sourcepub fn class_symbol(&self) -> RClass
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(())
}
sourcepub fn class_thread(&self) -> RClass
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(())
}
sourcepub fn class_time(&self) -> RClass
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(())
}
sourcepub fn class_true_class(&self) -> RClass
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(())
}
sourcepub fn class_unbound_method(&self) -> RClass
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
impl Ruby
sourcepub fn init(func: fn(_: &Ruby) -> Result<(), Error>) -> Result<(), String>
Available on crate feature embed
only.
pub fn init(func: fn(_: &Ruby) -> Result<(), Error>) -> Result<(), String>
embed
only.Initialises the Ruby VM.
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()
sourcepub fn script<T>(&self, name: T)where
T: IntoRString,
Available on crate feature embed
only.
pub fn script<T>(&self, name: T)where
T: IntoRString,
embed
only.Sets the current script name.
source§impl Ruby
impl Ruby
sourcepub fn enc_default_external(&self) -> Encoding
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.
sourcepub fn enc_default_internal(&self) -> Option<Encoding>
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
impl Ruby
sourcepub fn ascii8bit_encoding(&self) -> RbEncoding
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(())
}
sourcepub fn utf8_encoding(&self) -> RbEncoding
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(())
}
sourcepub fn usascii_encoding(&self) -> RbEncoding
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(())
}
sourcepub fn locale_encoding(&self) -> RbEncoding
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.
sourcepub fn filesystem_encoding(&self) -> RbEncoding
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.
sourcepub fn default_external_encoding(&self) -> RbEncoding
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.
sourcepub fn default_internal_encoding(&self) -> Option<RbEncoding>
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.
sourcepub fn find_encoding(&self, name: &str) -> Option<RbEncoding>
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
impl Ruby
sourcepub fn ascii8bit_encindex(&self) -> Index
pub fn ascii8bit_encindex(&self) -> Index
Returns the index for ASCII-8BIT a.k.a. binary.
sourcepub fn utf8_encindex(&self) -> Index
pub fn utf8_encindex(&self) -> Index
Returns the index for UTF-8.
sourcepub fn usascii_encindex(&self) -> Index
pub fn usascii_encindex(&self) -> Index
Returns the index for US-ASCII.
sourcepub fn locale_encindex(&self) -> Index
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.
sourcepub fn filesystem_encindex(&self) -> Index
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.
sourcepub fn find_encindex(&self, name: &str) -> Result<Index, Error>
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
impl Ruby
sourcepub fn iter_break_value<T>(&self, val: T) -> Errorwhere
T: IntoValue,
pub fn iter_break_value<T>(&self, val: T) -> Errorwhere
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§impl Ruby
impl Ruby
§Core Exceptions
Functions to access Ruby’s built-in exception classes.
See also the exception
module.
sourcepub fn exception_arg_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_eof_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_enc_compat_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_encoding_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_exception(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_fatal(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_float_domain_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_frozen_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_io_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_index_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_interrupt(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_key_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_load_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_local_jump_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_math_domain_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_name_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_no_matching_pattern_error(&self) -> ExceptionClass
Available on ruby_gte_2_7
only.
pub fn exception_no_matching_pattern_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_no_matching_pattern_key_error(&self) -> ExceptionClass
Available on ruby_gte_3_1
only.
pub fn exception_no_matching_pattern_key_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_no_mem_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_no_method_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_not_imp_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_range_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_regexp_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_runtime_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_script_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_security_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_signal(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_standard_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_stop_iteration(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_syntax_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_sys_stack_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_system_call_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_system_exit(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_thread_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_type_error(&self) -> ExceptionClass
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(())
}
sourcepub fn exception_zero_div_error(&self) -> ExceptionClass
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
impl Ruby
sourcepub fn float_from_f64(&self, n: f64) -> Float
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
impl Ruby
sourcepub fn gc_disable(&self) -> bool
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(())
}
sourcepub fn gc_enable(&self) -> bool
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(())
}
sourcepub fn gc_start(&self)
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(())
}
sourcepub fn gc_adjust_memory_usage(&self, diff: isize)
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(())
}
sourcepub fn gc_count(&self) -> usize
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(())
}
sourcepub fn gc_stat<T>(&self, key: T) -> Result<usize, Error>where
T: IntoSymbol,
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(())
}
sourcepub fn gc_all_stats(&self) -> RHash
pub fn gc_all_stats(&self) -> RHash
source§impl Ruby
impl Ruby
sourcepub fn integer_from_i64(&self, n: i64) -> Integer
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(())
}
sourcepub fn integer_from_u64(&self, n: u64) -> Integer
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
impl Ruby
sourcepub fn into_value<T>(&self, val: T) -> Valuewhere
T: IntoValue,
pub fn into_value<T>(&self, val: T) -> Valuewhere
T: IntoValue,
Convert val
into Value
.
source§impl Ruby
impl Ruby
sourcepub fn module_new(&self) -> RModule
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
impl Ruby
§Core Modules
Functions to access Ruby’s built-in modules.
See also Ruby::define_module
and the module
module.
sourcepub fn module_comparable(&self) -> RModule
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(())
}
sourcepub fn module_enumerable(&self) -> RModule
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(())
}
sourcepub fn module_errno(&self) -> RModule
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(())
}
sourcepub fn module_file_test(&self) -> RModule
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(())
}
sourcepub fn module_gc(&self) -> RModule
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(())
}
sourcepub fn module_kernel(&self) -> RModule
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(())
}
sourcepub fn module_math(&self) -> RModule
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(())
}
sourcepub fn module_process(&self) -> RModule
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(())
}
sourcepub fn module_wait_readable(&self) -> RModule
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(())
}
sourcepub fn module_wait_writable(&self) -> RModule
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
impl Ruby
sourcepub fn ary_new(&self) -> RArray
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(())
}
sourcepub fn ary_new_capa(&self, n: usize) -> RArray
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(())
}
sourcepub fn ary_from_vec<T>(&self, vec: Vec<T>) -> RArraywhere
T: IntoValueFromNative,
pub fn ary_from_vec<T>(&self, vec: Vec<T>) -> RArraywhere
T: IntoValueFromNative,
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(())
}
sourcepub fn ary_new_from_values<T>(&self, slice: &[T]) -> RArraywhere
T: ReprValue,
pub fn ary_new_from_values<T>(&self, slice: &[T]) -> RArraywhere
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(())
}
sourcepub fn ary_from_iter<I, T>(&self, iter: I) -> RArraywhere
I: IntoIterator<Item = T>,
T: IntoValue,
pub fn ary_from_iter<I, T>(&self, iter: I) -> RArraywhere
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
impl Ruby
§RBignum
Functions that can be used to create instances of Ruby’s large interger representation.
See also the RBignum
type.
sourcepub fn bignum_from_i64(&self, n: i64) -> Result<RBignum, Fixnum>
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(())
}
sourcepub fn bignum_from_u64(&self, n: u64) -> Result<RBignum, Fixnum>
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
impl Ruby
sourcepub fn r_float_from_f64(&self, n: f64) -> Result<RFloat, Flonum>
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
impl Ruby
sourcepub fn hash_new(&self) -> RHash
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(())
}
sourcepub fn hash_new_capa(&self, n: usize) -> RHash
Available on ruby_gte_3_2
only.
pub fn hash_new_capa(&self, n: usize) -> RHash
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
impl Ruby
sourcepub fn rational_new(&self, num: i64, den: NonZeroI64) -> RRational
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
impl Ruby
sourcepub fn reg_new(&self, pattern: &str, opts: Opts) -> Result<RRegexp, Error>
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
impl Ruby
sourcepub fn str_new(&self, s: &str) -> RString ⓘ
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(())
}
sourcepub fn str_buf_new(&self, n: usize) -> RString ⓘ
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(())
}
sourcepub fn str_with_capacity(&self, n: usize) -> RString ⓘ
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(())
}
sourcepub fn str_from_slice(&self, s: &[u8]) -> RString ⓘ
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(())
}
sourcepub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString ⓘ
pub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString ⓘ
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(())
}
sourcepub fn str_from_char(&self, c: char) -> RString ⓘ
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(())
}
sourcepub fn chr<T>(&self, code: u32, enc: T) -> Result<RString, Error>where
T: Into<RbEncoding>,
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
impl Ruby
sourcepub fn define_struct<T>(
&self,
name: Option<&str>,
members: T
) -> Result<RClass, Error>where
T: StructMembers,
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
impl Ruby
§RTypedData
Functions to wrap Rust data in a Ruby object.
See also typed_data::Obj
and the RTypedData
type.
sourcepub fn wrap<T>(&self, data: T) -> RTypedDatawhere
T: TypedData,
pub fn wrap<T>(&self, data: T) -> RTypedDatawhere
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(())
}
sourcepub fn wrap_as<T>(&self, data: T, class: RClass) -> RTypedDatawhere
T: TypedData,
pub fn wrap_as<T>(&self, data: T, class: RClass) -> RTypedDatawhere
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
impl Ruby
sourcepub fn range_new<T, U>(
&self,
beg: T,
end: U,
excl: bool
) -> Result<Range, Error>
pub fn range_new<T, U>( &self, beg: T, end: U, excl: bool ) -> Result<Range, Error>
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
impl Ruby
sourcepub fn check_arity<T>(&self, len: usize, bounds: T) -> Result<(), Error>where
T: RangeBounds<usize>,
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
impl Ruby
§typed_data::Obj
Functions to wrap Rust data in a Ruby object.
See also RTypedData
and the typed_data::Obj
type.
sourcepub fn obj_wrap<T>(&self, data: T) -> Obj<T>where
T: TypedData,
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(())
}
sourcepub fn obj_wrap_as<T>(&self, data: T, class: RClass) -> Obj<T>where
T: TypedData,
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
impl Ruby
§Flonum
Functions that can be used to create instances of Ruby’s lower precision floating point representation.
See also the Flonum
type.
sourcepub fn flonum_from_f64(&self, n: f64) -> Result<Flonum, RFloat>
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
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.
sourcepub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> Twhere
T: ReprValue,
pub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> Twhere
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§impl Ruby
impl Ruby
§Fixnum
Functions that can be used to create instances of Ruby’s small/fast integer representation.
See also the Fixnum
type.
sourcepub fn fixnum_from_i64(&self, n: i64) -> Result<Fixnum, RBignum>
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(())
}
sourcepub fn fixnum_from_u64(&self, n: u64) -> Result<Fixnum, RBignum>
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
impl Ruby
§StaticSymbol
Functions to create Ruby Symbol
s that will never be garbage collected.
See also the StaticSymbol
type.
sourcepub fn sym_new<T>(&self, name: T) -> StaticSymbolwhere
T: IntoId,
pub fn sym_new<T>(&self, name: T) -> StaticSymbolwhere
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(())
}
sourcepub fn check_symbol(&self, name: &str) -> Option<StaticSymbol>
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
impl Ruby
source§impl Ruby
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.
sourcepub fn define_class(
&self,
name: &str,
superclass: RClass
) -> Result<RClass, Error>
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(())
}
sourcepub fn define_module(&self, name: &str) -> Result<RModule, Error>
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(())
}
sourcepub fn define_error(
&self,
name: &str,
superclass: ExceptionClass
) -> Result<ExceptionClass, Error>
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(())
}
sourcepub fn define_variable<T>(
&self,
name: &str,
initial: T
) -> Result<*mut Value, Error>where
T: IntoValue,
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(())
}
sourcepub fn define_global_const<T>(&self, name: &str, value: T) -> Result<(), Error>where
T: IntoValue,
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(())
}
sourcepub fn define_global_function<M>(&self, name: &str, func: M)where
M: Method,
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(())
}
sourcepub fn backref_get(&self) -> Option<RMatch>
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(())
}
sourcepub fn current_receiver<T>(&self) -> Result<T, Error>where
T: TryConvert,
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(())
}
sourcepub fn call_super<A, T>(&self, args: A) -> Result<T, Error>where
A: ArgList,
T: TryConvert,
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(())
}
sourcepub fn require<T>(&self, feature: T) -> Result<bool, Error>where
T: IntoRString,
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(())
}
sourcepub fn eval<T>(&self, s: &str) -> Result<T, Error>where
T: TryConvert,
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(())
}