Struct magnus::value::Value

source ·
#[repr(transparent)]
pub struct Value(_);
Expand description

Ruby’s VALUE type, which can represent any Ruby object.

Implementations§

Returns whether self is Ruby’s nil value.

Examples
use magnus::{eval, Value};

assert!(eval::<Value>("nil").unwrap().is_nil());
assert!(!eval::<Value>("Object.new").unwrap().is_nil());
assert!(!eval::<Value>("0").unwrap().is_nil());
assert!(!eval::<Value>("[]").unwrap().is_nil());

Checks for equality, delegating to the Ruby method #==.

Ruby optimises this check if self and other are the same object or some built-in types, then calling the #== method will be skipped.

Returns Err if #== raises.

Examples
use magnus::{Integer, RArray};

let a = RArray::from_vec(vec![1, 2, 3]);
let b = RArray::from_vec(vec![1, 2, 3]);
let c = RArray::from_vec(vec![4, 5, 6]);
let d = Integer::from_i64(1);
assert!(a.equal(a).unwrap());
assert!(a.equal(b).unwrap());
assert!(!a.equal(c).unwrap());
assert!(!a.equal(d).unwrap());
use magnus::{eval, Value};

let (a, b): (Value, Value) = eval!("
    class Example
      def ==(other)
        raise
      end
    end
    [Example.new, Example.new]
").unwrap();

assert!(a.equal(&b).is_err());

Checks for equality, delegating to the Ruby method #eql?.

See Value::equal for the equivalent of the #== method.

Ruby optimises this check if self and other are the same object or some built-in types, then calling the #== method will be skipped.

Returns Err if #eql? raises.

Examples
use magnus::{Integer, RArray};

let a = RArray::from_vec(vec![1, 2, 3]);
let b = RArray::from_vec(vec![1, 2, 3]);
let c = RArray::from_vec(vec![4, 5, 6]);
let d = Integer::from_i64(1);
assert!(a.eql(a).unwrap());
assert!(a.eql(b).unwrap());
assert!(!a.eql(c).unwrap());
assert!(!a.eql(d).unwrap());
use magnus::{eval, Value};

let (a, b): (Value, Value) = eval!("
    class Example
      def eql?(other)
        raise
      end
    end
    [Example.new, Example.new]
").unwrap();

assert!(a.eql(&b).is_err());

Returns the class that self is an instance of.

Panics

panics if self is Qundef.

Examples
use magnus::{eval, Value};

assert_eq!(eval::<Value>("true").unwrap().class().inspect(), "TrueClass");
assert_eq!(eval::<Value>("[1,2,3]").unwrap().class().inspect(), "Array");

Returns whether self is ‘frozen’.

Ruby prevents modifying frozen objects.

Examples
use magnus::{eval, Value};

assert!(eval::<Value>(":foo").unwrap().is_frozen());
assert!(eval::<Value>("42").unwrap().is_frozen());
assert!(!eval::<Value>("[]").unwrap().is_frozen());

Returns an error if self is ‘frozen’.

Useful for checking if an object is frozen in a function that would modify it.

Examples
use magnus::{eval, Error, Value};

fn mutate(val: Value) -> Result<(), Error> {
    val.check_frozen()?;

    /// ...

    Ok(())
}

assert!(mutate(eval("Object.new").unwrap()).is_ok());
assert!(mutate(eval(":foo").unwrap()).is_err());

Mark self as frozen.

Examples
use magnus::{eval, RArray};

let ary = RArray::new();
assert!(!ary.is_frozen());
ary.freeze();
assert!(ary.is_frozen());

Convert self to a bool, following Ruby’s rules of false and nil as boolean false and everything else boolean true.

Examples
use magnus::{eval, Value};

assert!(!eval::<Value>("false").unwrap().to_bool());
assert!(!eval::<Value>("nil").unwrap().to_bool());

assert!(eval::<Value>("true").unwrap().to_bool());
assert!(eval::<Value>("0").unwrap().to_bool());
assert!(eval::<Value>("[]").unwrap().to_bool());
assert!(eval::<Value>(":foo").unwrap().to_bool());
assert!(eval::<Value>("Object.new").unwrap().to_bool());

Call the method named method on self with args.

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

Examples
use magnus::{eval, RArray};

let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
let result: String = values.funcall("join", (" & ",)).unwrap();
assert_eq!(result, "foo & 1 & bar");

If self responds to the method named method, call it with args.

Returns Some(Ok(T)) if the method exists and returns without error, None if it does not exist, or Some(Err) if an exception was raised.

Examples
use magnus::{Float, Integer, RString};

let val = Float::from_f64(1.23);
let res: Integer = val.check_funcall("to_int", ()).unwrap().unwrap();
assert_eq!(res.to_i64().unwrap(), 1);

let val = RString::new("1.23");
let res: Option<Result<Integer, _>> = val.check_funcall("to_int", ());
assert!(res.is_none());

Call the method named method on self with args and block.

Similar to funcall, but passes block as a Ruby block to the method.

See also block_call.

Examples
use magnus::{eval, block::Proc, RArray, Value};

let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
let block = Proc::new(|args, _block| args.first().unwrap().to_r_string());
let _: Value = values.funcall_with_block("map!", (), block).unwrap();
assert_eq!(values.to_vec::<String>().unwrap(), vec!["foo", "1", "bar"]);

Call the method named method on self with args and block.

Similar to funcall, but passes block as a Ruby block to the method.

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 and funcall_with_block.

The function passed as block will receive values yielded to the block as a slice of Values, plus Some(Proc) if the block itself was called with a block, or None otherwise.

The block function may return any R or Result<R, Error> where R implements Into<Value>. Returning Err(Error) will raise the error as a Ruby exception.

Examples
use magnus::{eval, RArray, Value};

let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
let _: Value = values.block_call("map!", (), |args, _block| args.first().unwrap().to_r_string()).unwrap();
assert_eq!(values.to_vec::<String>().unwrap(), vec!["foo", "1", "bar"]);

Check if self responds to the given Ruby method.

The include_private agument controls whether self’s private methods are checked. If false they are not, if true they are.

See also Value::check_funcall.

Examples
use magnus::RString;

let s = RString::new("example");
assert!(s.respond_to("to_str", false).unwrap());
assert!(!s.respond_to("puts", false).unwrap());
assert!(s.respond_to("puts", true).unwrap());
assert!(!s.respond_to("non_existant", false).unwrap());
assert!(!s.respond_to("non_existant", true).unwrap());

Convert self to a Ruby String.

If self is already a String is it wrapped as a RString, otherwise the Ruby to_s method is called.

Examples
use magnus::{eval, class, Value};

let value = eval::<Value>("[]").unwrap();
assert!(value.to_r_string().unwrap().is_kind_of(class::string()));

Convert self to a Rust string.

Safety

This may return a direct view of memory owned and managed by Ruby. Ruby may modify or free the memory backing the returned str, the caller must ensure this does not happen.

This can be used safely by immediately calling into_owned on the return value.

Examples
use magnus::{eval, QTRUE};

let value = QTRUE;
// safe as we neve give Ruby a chance to free the string.
let s = unsafe { value.to_s() }.unwrap().into_owned();
assert_eq!(s, "true");

Convert self to its Ruby debug representation.

Examples
use magnus::{eval, Symbol, QNIL};

assert_eq!(QNIL.inspect(), "nil");
assert_eq!(Symbol::new("foo").inspect(), ":foo");

Return the name of self’s class.

Safety

Ruby may modify or free the memory backing the returned str, the caller must ensure this does not happen.

This can be used safely by immediately calling into_owned on the return value.

Examples
use magnus::{eval, RHash};

let value = RHash::new();
// safe as we never give Ruby a chance to free the string.
let s = unsafe { value.classname() }.into_owned();
assert_eq!(s, "Hash");

Returns whether or not self is an instance of class.

Examples
use magnus::{class, eval, Value};

let value = eval::<Value>("[]").unwrap();
assert!(value.is_kind_of(class::array()));

Generate an Enumerator from method on self, passing args to method.

Examples
use magnus::{class, eval, r_string};

let s = r_string!("foo\\bar\\baz");
let mut i = 0;
for line in s.enumeratorize("each_line", ("\\",)) {
    assert!(line.unwrap().is_kind_of(class::string()));
    i += 1;
}
assert_eq!(i, 3);

Convert self to the Rust type T.

See the types that TryConvert is implemented on for what this method can convert to.

Examples
use magnus::{eval, Value};

assert_eq!(eval::<Value>("42").unwrap().try_convert::<i64>().unwrap(), 42);
assert_eq!(eval::<Value>("1.23").unwrap().try_convert::<i64>().unwrap(), 1);
assert_eq!(eval::<Value>("1").unwrap().try_convert::<f64>().unwrap(), 1.0);
assert_eq!(eval::<Value>("nil").unwrap().try_convert::<Option<i64>>().unwrap(), None);
assert_eq!(eval::<Value>("42").unwrap().try_convert::<Option<i64>>().unwrap(), Some(42));

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Convert val into Self.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.