#[repr(transparent)]
pub struct RHash(_);
Expand description

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

All Value methods should be available on this type through Deref, but some may be missed by this documentation.

Implementations

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());

Create a new empty RHash.

Examples
use magnus::RHash;

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

Set the value val for the key key.

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

Examples
use magnus::{eval, RHash};

let hash = RHash::new();
hash.aset("answer", 42);
let res: bool = eval!(r#"hash == {"answer" => 42}"#, hash).unwrap();
assert!(res);

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);
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 = eval::<RHash>(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);

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 = eval::<RHash>(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);

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);
assert!(hash.get("answer").is_some());
assert!(hash.get("missing").is_none());

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, value::Qnil, RHash};

let hash = eval::<RHash>(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());

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 = eval::<RHash>(r#"hash = {"answer" => 42}"#).unwrap();
assert_eq!(hash.delete::<_, i64>("answer").unwrap(), 42);
assert!(hash.delete::<_, Qnil>("answer").is_ok());

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());

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 = eval::<RHash>(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")));

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 = eval::<RHash>(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);

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 std::collections::HashMap;
use magnus::{eval, RHash};

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

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

Examples
use magnus::{eval, RHash};

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

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

Examples
use magnus::{eval, RHash};

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

Return whether self contains any entries or not.

Examples
use magnus::RHash;

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

Methods from Deref<Target = Value>

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");

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 neve give Ruby a chance to free the string.
let s = unsafe { value.classname() }.into_owned();
assert_eq!(s, "Hash");

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

The resulting type after dereferencing.

Dereferences the value.

Formats the value using the given formatter. Read more

Converts to this type from the input type.

Creates a value from an iterator. Read more

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

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

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

Finds or creates the singleton class of self. Read more

Extend self with module. Read more

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

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.