Struct magnus::r_hash::RHash

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

A Value pointer to a RHash struct, Ruby’s internal representation of Hash objects.

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

Implementations§

source§

impl RHash

source

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

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

§Examples
use magnus::{eval, RHash};

assert!(RHash::from_value(eval(r#"{"answer" => 42}"#).unwrap()).is_some());
assert!(RHash::from_value(eval("[]").unwrap()).is_none());
assert!(RHash::from_value(eval("nil").unwrap()).is_none());
source

pub fn new() -> RHash

Create a new empty RHash.

§Panics

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

§Examples
use magnus::RHash;

let hash = RHash::new();
assert!(hash.is_empty());
source

pub fn with_capacity(n: usize) -> Self

Available on ruby_gte_3_2 only.

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

§Panics

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

§Examples
use magnus::RHash;

let ary = RHash::with_capacity(16);
assert!(ary.is_empty());
source

pub fn aset<K, V>(self, key: K, val: V) -> Result<(), Error>
where K: IntoValue, V: IntoValue,

Set the value val for the key key.

Errors if self is frozen or key does not respond to hash.

§Examples
use magnus::{rb_assert, RHash};

let hash = RHash::new();
hash.aset("answer", 42).unwrap();
rb_assert!(r#"hash == {"answer" => 42}"#, hash);
source

pub fn bulk_insert<T>(self, slice: &[T]) -> Result<(), Error>
where T: ReprValue,

Available on ruby_gte_2_7 only.

Insert a list of key-value pairs into a hash at once.

§Examples
use magnus::{prelude::*, rb_assert, RHash, RString, Symbol};

let hash = RHash::new();
hash.bulk_insert(&[
    Symbol::new("given_name").as_value(),
    RString::new("Arthur").as_value(),
    Symbol::new("family_name").as_value(),
    RString::new("Dent").as_value(),
])
.unwrap();
rb_assert!(
    r#"hash == {given_name: "Arthur", family_name: "Dent"}"#,
    hash,
);
source

pub fn update(self, other: RHash) -> Result<(), Error>

Merges two hashes into one.

§Examples
use magnus::{eval, rb_assert, RHash};

let a: RHash = eval("{a: 1, b: 2}").unwrap();
let b: RHash = eval("{b: 3, c: 4}").unwrap();
a.update(b).unwrap();

// a is mutated, in case of conflicts b wins
rb_assert!("a == {a: 1, b: 3, c: 4}", a);

// b is unmodified
rb_assert!("b == {b: 3, c: 4}", b);
source

pub fn aref<T, U>(self, key: T) -> Result<U, Error>
where T: IntoValue, U: TryConvert,

Return the value for key, converting it to U.

Returns hash’s default if key is missing. See also lookup, get, and fetch.

§Examples
use magnus::{value::Qnil, RHash};

let hash = RHash::new();
hash.aset("answer", 42).unwrap();
assert_eq!(hash.aref::<_, i64>("answer").unwrap(), 42);
assert!(hash.aref::<_, Qnil>("missing").is_ok());
assert_eq!(hash.aref::<_, Option<i64>>("answer").unwrap(), Some(42));
assert_eq!(hash.aref::<_, Option<i64>>("missing").unwrap(), None);
use magnus::{eval, RHash};

let hash: RHash = eval(
    r#"
      hash = {"answer" => 42}
      hash.default = 0
      hash
    "#,
)
.unwrap();
assert_eq!(hash.aref::<_, i64>("answer").unwrap(), 42);
assert_eq!(hash.aref::<_, i64>("missing").unwrap(), 0);
assert_eq!(hash.aref::<_, i64>(()).unwrap(), 0);
source

pub fn lookup<T, U>(self, key: T) -> Result<U, Error>
where T: IntoValue, U: TryConvert,

Return the value for key, converting it to U.

Returns nil if key is missing. See also aref, get, and fetch.

§Examples
use magnus::{eval, value::Qnil, RHash};

let hash: RHash = eval(
    r#"
      hash = {"answer" => 42}
      hash.default = 0
      hash
    "#,
)
.unwrap();
assert_eq!(hash.lookup::<_, i64>("answer").unwrap(), 42);
assert!(hash.lookup::<_, Qnil>("missing").is_ok());
assert_eq!(hash.lookup::<_, Option<i64>>("answer").unwrap(), Some(42));
assert_eq!(hash.lookup::<_, Option<i64>>("missing").unwrap(), None);
source

pub fn get<T>(self, key: T) -> Option<Value>
where T: IntoValue,

Return the value for key as a Value.

Returns None if key is missing. See also aref, lookup, and fetch.

Note: It is possible for very badly behaved key objects to raise an error during hash lookup. This is unlikely, and for the simplicity of this api any errors will result in None.

§Examples
use magnus::RHash;

let hash = RHash::new();
hash.aset("answer", 42).unwrap();
assert!(hash.get("answer").is_some());
assert!(hash.get("missing").is_none());
source

pub fn fetch<T, U>(self, key: T) -> Result<U, Error>
where T: IntoValue, U: TryConvert,

Return the value for key, converting it to U.

Returns Err if key is missing. See also aref, lookup, and get.

§Examples
use magnus::{eval, RHash};

let hash: RHash = eval(
    r#"
      hash = {"answer" => 42}
      hash.default = 0
      hash
    "#,
)
.unwrap();
assert_eq!(hash.fetch::<_, i64>("answer").unwrap(), 42);
assert!(hash.fetch::<_, i64>("missing").is_err());
assert_eq!(hash.fetch::<_, Option<i64>>("answer").unwrap(), Some(42));
assert!(hash.fetch::<_, Option<i64>>("missing").is_err());
source

pub fn delete<T, U>(self, key: T) -> Result<U, Error>
where T: IntoValue, U: TryConvert,

Removes the key key from self and returns the associated value, converting it to U.

Returns nil if key is missing.

§Examples
use magnus::{eval, value::Qnil, RHash};

let hash: RHash = eval(r#"hash = {"answer" => 42}"#).unwrap();
assert_eq!(hash.delete::<_, i64>("answer").unwrap(), 42);
assert!(hash.delete::<_, Qnil>("answer").is_ok());
source

pub fn clear(self) -> Result<(), Error>

Removes all entries from self.

Errors if self is frozen.

§Examples
use magnus::{eval, RHash};

let hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
assert!(!hash.is_empty());
hash.clear().unwrap();
assert!(hash.is_empty());
source

pub fn foreach<F, K, V>(self, func: F) -> Result<(), Error>
where F: FnMut(K, V) -> Result<ForEach, Error>, K: TryConvert, V: TryConvert,

Run func for each key/value pair in self.

The result of func is checked on each call, when it is ForEach::Continue the iteration will continue, ForEach::Stop will cause the iteration to stop, and ForEach::Delete will remove the key/value pair from self and then continue iteration.

Returing an error from func behaves like ForEach::Stop.

§Examples
use magnus::{eval, r_hash::ForEach, RHash};

let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4, "qux" => 8}"#).unwrap();
let mut found = None;
hash.foreach(|key: String, value: i64| {
    if value > 3 {
        found = Some(key);
        Ok(ForEach::Stop)
    } else {
        Ok(ForEach::Continue)
    }
})
.unwrap();
assert_eq!(found, Some(String::from("baz")));
source

pub fn to_hash_map<K, V>(self) -> Result<HashMap<K, V>, Error>

Return self converted to a Rust HashMap.

This will only convert to a map of ‘owned’ Rust native types. The types representing Ruby objects can not be stored in a heap-allocated datastructure like a HashMap as they are hidden from the mark phase of Ruby’s garbage collector, and thus may be prematurely garbage collected in the following sweep phase.

Errors if the conversion of any key or value fails.

§Examples
use std::collections::HashMap;

use magnus::{eval, RHash};

let r_hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
let mut hash_map = HashMap::new();
hash_map.insert(String::from("answer"), 42);
assert_eq!(r_hash.to_hash_map().unwrap(), hash_map);
source

pub fn to_vec<K, V>(self) -> Result<Vec<(K, V)>, Error>

Convert self to a Rust vector of key/value pairs.

This will only convert to a map of ‘owned’ Rust native types. The types representing Ruby objects can not be stored in a heap-allocated datastructure like a Vec as they are hidden from the mark phase of Ruby’s garbage collector, and thus may be prematurely garbage collected in the following sweep phase.

Errors if the conversion of any key or value fails.

§Examples
use magnus::{eval, RHash};

let r_hash: RHash = eval(r#"{"answer" => 42}"#).unwrap();
assert_eq!(r_hash.to_vec().unwrap(), vec![(String::from("answer"), 42)]);
source

pub fn size(self) -> Fixnum

Return the number of entries in self as a Ruby Fixnum.

§Examples
use magnus::{eval, RHash};

let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#).unwrap();
assert_eq!(hash.size().to_i64(), 3);
source

pub fn len(self) -> usize

Return the number of entries in self as a Rust usize.

§Examples
use magnus::{eval, RHash};

let hash: RHash = eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#).unwrap();
assert_eq!(hash.len(), 3);
source

pub fn is_empty(self) -> bool

Return whether self contains any entries or not.

§Examples
use magnus::RHash;

let hash = RHash::new();
assert!(hash.is_empty());
hash.aset("answer", 42).unwrap();
assert!(!hash.is_empty());

Trait Implementations§

source§

impl Clone for RHash

source§

fn clone(&self) -> RHash

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 RHash

source§

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

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

impl Display for RHash

source§

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

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

impl<K, V> FromIterator<(K, V)> for RHash
where K: IntoValue, V: IntoValue,

source§

fn from_iter<I>(iter: I) -> Self
where I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl IntoValue for RHash

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 RHash

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 RHash

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 RHash

source§

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

Convert val into Self.
source§

impl Copy for RHash

Auto Trait Implementations§

§

impl Freeze for RHash

§

impl RefUnwindSafe for RHash

§

impl Send for RHash

§

impl Sync for RHash

§

impl Unpin for RHash

§

impl UnwindSafe for RHash

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