Struct magnus::block::Proc

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

Wrapper type for a Value known to be an instance of Ruby’s Proc class.

See the ReprValue and Object traits for additional methods available on this type. See Ruby for methods to create a Proc.

Implementations§

source§

impl Proc

source

pub fn from_value(val: Value) -> Option<Self>

Return Some(Proc) if val is a Proc, None otherwise.

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

let val: Value = eval("Proc.new {|a, b| a + b}").unwrap();
assert!(Proc::from_value(val).is_some());

let val: Value = eval("1 + 2").unwrap();
assert!(Proc::from_value(val).is_none());
source

pub fn new<R>(block: fn(_: &[Value], _: Option<Proc>) -> R) -> Self
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 from_fn.

§Panics

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

§Examples
use magnus::{block::Proc, prelude::*, rb_assert};

let proc = 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!("proc.call(1, 2) == 3", proc);

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

pub fn from_fn<F, R>(block: F) -> Self
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.

§Panics

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

§Examples
use magnus::{block::Proc, prelude::*, rb_assert};

let mut count = 0;

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

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

pub fn call<A, T>(self, args: A) -> Result<T, Error>

Call the proc with args.

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

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

let proc: Proc = eval("Proc.new {|a, b| a + b}").unwrap();

// call with a tuple
let result: i64 = proc.call((1, 2)).unwrap();
assert_eq!(3, result);

// call with a slice
let result: i64 = proc
    .call(&[Integer::from_i64(3), Integer::from_i64(4)][..])
    .unwrap();
assert_eq!(7, result);

// call with an array
let result: i64 = proc
    .call([Integer::from_i64(5), Integer::from_i64(6)])
    .unwrap();
assert_eq!(11, result);

// call with a Ruby array
let array = RArray::from_vec(vec![7, 8]);
let result: i64 = proc.call(array).unwrap();
assert_eq!(15, result);

With keyword arguments:

use magnus::{block::Proc, eval, kwargs};

let proc: Proc = eval("Proc.new {|a, b:, c:| a + b + c}").unwrap();

let result: i64 = proc.call((1, kwargs!("b" => 2, "c" => 3))).unwrap();
assert_eq!(6, result);

Ignoring return value:

use magnus::{block::Proc, eval, rb_assert, Value};

let proc: Proc = eval("Proc.new { $called = true }").unwrap();

let _: Value = proc.call(()).unwrap();

rb_assert!("$called == true");
source

pub fn arity(self) -> i64

Returns the number of arguments self takes.

If self takes no arguments, returns 0. If self takes only required arguments, returns the number of required arguments. If self is a lambda and has optional arguments, or is not a lambda and takes a splat argument, returns -n-1, where n is the number of required arguments. If self is not a lambda, and takes a finite number of optional arguments, returns the number of required arguments. Keyword arguments are considered as a single additional argument, that argument being required if any keyword argument is required.

§Examples
use magnus::{block::Proc, eval};

let proc: Proc = eval("proc {nil}").unwrap();
assert_eq!(proc.arity(), 0);

let proc: Proc = eval("proc {|a| a + 1}").unwrap();
assert_eq!(proc.arity(), 1);

let proc: Proc = eval("proc {|a, b| a + b}").unwrap();
assert_eq!(proc.arity(), 2);

let proc: Proc = eval("proc {|*args| args.sum}").unwrap();
assert_eq!(proc.arity(), -1);
source

pub fn is_lambda(self) -> bool

Returns whether or not self is a lambda.

§Examples
use magnus::{block::Proc, eval};

let proc: Proc = eval("proc {|a, b| a + b}").unwrap();
assert!(!proc.is_lambda());

let proc: Proc = eval("lambda {|a, b| a + b}").unwrap();
assert!(proc.is_lambda());

Trait Implementations§

source§

impl Clone for Proc

source§

fn clone(&self) -> Proc

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Proc

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Proc

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl IntoValue for Proc

source§

fn into_value_with(self, _: &Ruby) -> Value

Convert self into Value.
source§

fn into_value(self) -> Value

Convert self into Value. Read more
source§

unsafe fn into_value_unchecked(self) -> Value

Convert self into Value. Read more
source§

impl Object for Proc

source§

fn define_singleton_method<M>(self, name: &str, func: M) -> Result<(), Error>
where M: Method,

Define a singleton method in self’s scope. Read more
source§

fn ivar_get<T, U>(self, name: T) -> Result<U, Error>
where T: IntoId, U: TryConvert,

Get the value for the instance variable name within self’s scope. Read more
source§

fn ivar_set<T, U>(self, name: T, value: U) -> Result<(), Error>
where T: IntoId, U: IntoValue,

Set the value for the instance variable name within self’s scope. Read more
source§

fn singleton_class(self) -> Result<RClass, Error>

Finds or creates the singleton class of self. Read more
source§

fn extend_object(self, module: RModule) -> Result<(), Error>

Extend self with module. Read more
source§

impl ReprValue for Proc

source§

fn as_value(self) -> Value

Return self as a Value.
source§

fn is_nil(self) -> bool

Returns whether self is Ruby’s nil value. Read more
source§

fn equal<T>(self, other: T) -> Result<bool, Error>
where T: ReprValue,

Checks for equality, delegating to the Ruby method #==. Read more
source§

fn eql<T>(self, other: T) -> Result<bool, Error>
where T: ReprValue,

Checks for equality, delegating to the Ruby method #eql?. Read more
source§

fn hash(self) -> Result<Integer, Error>

Returns an integer non-uniquely identifying self. Read more
source§

fn class(self) -> RClass

Returns the class that self is an instance of. Read more
source§

fn is_frozen(self) -> bool

Returns whether self is ‘frozen’. Read more
source§

fn check_frozen(self) -> Result<(), Error>

Returns an error if self is ‘frozen’. Read more
source§

fn freeze(self)

Mark self as frozen. Read more
source§

fn to_bool(self) -> bool

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

fn funcall<M, A, T>(self, method: M, args: A) -> Result<T, Error>
where M: IntoId, A: ArgList, T: TryConvert,

Call the method named method on self with args. Read more
source§

fn funcall_public<M, A, T>(self, method: M, args: A) -> Result<T, Error>
where M: IntoId, A: ArgList, T: TryConvert,

Call the public method named method on self with args. Read more
source§

fn check_funcall<M, A, T>(self, method: M, args: A) -> Option<Result<T, Error>>
where M: IntoId, A: ArgList, T: TryConvert,

If self responds to the method named method, call it with args. Read more
source§

fn funcall_with_block<M, A, T>( self, method: M, args: A, block: Proc ) -> Result<T, Error>
where M: IntoId, A: ArgList, T: TryConvert,

Call the method named method on self with args and block. Read more
source§

fn block_call<M, A, R, T>( self, method: M, args: A, block: fn(_: &[Value], _: Option<Proc>) -> R ) -> Result<T, Error>
where M: IntoId, A: ArgList, R: BlockReturn, T: TryConvert,

Call the method named method on self with args and block. Read more
source§

fn respond_to<M>(self, method: M, include_private: bool) -> Result<bool, Error>
where M: IntoId,

Check if self responds to the given Ruby method. Read more
source§

fn to_r_string(self) -> Result<RString, Error>

Convert self to a Ruby String. Read more
source§

unsafe fn to_s(&self) -> Result<Cow<'_, str>, Error>

Convert self to a Rust string. Read more
source§

fn inspect(self) -> String

Convert self to its Ruby debug representation. Read more
source§

unsafe fn classname(&self) -> Cow<'_, str>

Return the name of self’s class. Read more
source§

fn is_kind_of<T>(self, class: T) -> bool
where T: ReprValue + Module,

Returns whether or not self is an instance of class. Read more
source§

fn enumeratorize<M, A>(self, method: M, args: A) -> Enumerator
where M: IntoSymbol, A: ArgList,

Generate an Enumerator from method on self, passing args to method. Read more
source§

impl TryConvert for Proc

source§

fn try_convert(val: Value) -> Result<Self, Error>

Convert val into Self.
source§

impl Copy for Proc

Auto Trait Implementations§

§

impl Freeze for Proc

§

impl RefUnwindSafe for Proc

§

impl Send for Proc

§

impl Sync for Proc

§

impl Unpin for Proc

§

impl UnwindSafe for Proc

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> AsRawValue for T
where T: ReprValue,

source§

fn as_raw(self) -> u64

Available on crate feature rb-sys only.
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> Inspect for T
where T: Debug,

source§

fn inspect(&self) -> String

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> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
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.
source§

impl<T> BlockReturn for T
where T: BlockReturn,

source§

impl<T> Locate for T
where T: ReprValue,

source§

impl<T> Mark for T
where T: ReprValue,

source§

impl<T> ReturnValue for T
where T: ReturnValue,

source§

impl<T> ScanArgsBlock for T
where T: ScanArgsBlock,