pub struct RString(/* private fields */);
Expand description
Implementations§
source§impl RString
impl RString
sourcepub fn from_value(val: Value) -> Option<Self>
pub fn from_value(val: Value) -> Option<Self>
Return Some(RString)
if val
is a RString
, None
otherwise.
§Examples
use magnus::{eval, RString};
assert!(RString::from_value(eval(r#""example""#).unwrap()).is_some());
assert!(RString::from_value(eval(":example").unwrap()).is_none());
sourcepub fn new(s: &str) -> Self
pub fn new(s: &str) -> Self
Create a new Ruby string from the Rust string s
.
The encoding of the Ruby string will be UTF-8.
§Panics
Panics if called from a non-Ruby thread. See Ruby::str_new
for the
non-panicking version.
§Examples
use magnus::{rb_assert, RString};
let val = RString::new("example");
rb_assert!(r#"val == "example""#, val);
sourcepub fn buf_new(n: usize) -> Self
pub fn buf_new(n: usize) -> Self
Create a new Ruby string with capacity n
.
The encoding will be set to ASCII-8BIT (aka BINARY). See also
with_capacity
.
§Panics
Panics if called from a non-Ruby thread. See Ruby::str_buf_new
for
the non-panicking version.
§Examples
use magnus::{rb_assert, RString};
let buf = RString::buf_new(4096);
buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
rb_assert!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
sourcepub fn with_capacity(n: usize) -> Self
pub fn with_capacity(n: usize) -> Self
Create a new Ruby string with capacity n
.
The encoding will be set to UTF-8. See also
buf_new
.
§Panics
Panics if called from a non-Ruby thread. See
Ruby::str_with_capacity
for the non-panicking version.
§Examples
use magnus::{rb_assert, RString};
let s = RString::with_capacity(9);
s.cat("foo");
s.cat("bar");
s.cat("baz");
rb_assert!(r#"s == "foobarbaz""#, s);
sourcepub fn from_slice(s: &[u8]) -> Self
pub fn from_slice(s: &[u8]) -> Self
Create a new Ruby string from the Rust slice s
.
The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).
§Panics
Panics if called from a non-Ruby thread. See Ruby::str_from_slice
for the non-panicking version.
§Examples
use magnus::{rb_assert, RString};
let buf = RString::from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
rb_assert!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
sourcepub fn enc_new<T, E>(s: T, enc: E) -> Self
pub fn enc_new<T, E>(s: T, enc: E) -> Self
Create a new Ruby string from the value s
with the encoding enc
.
§Panics
Panics if called from a non-Ruby thread. See Ruby::enc_str_new
for
the non-panicking version.
§Examples
use magnus::{encoding::RbEncoding, rb_assert, RString};
let val = RString::enc_new("example", RbEncoding::usascii());
rb_assert!(r#"val == "example""#, val);
use magnus::{encoding::RbEncoding, rb_assert, RString};
let val = RString::enc_new([255, 128, 128], RbEncoding::ascii8bit());
rb_assert!(r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#, val);
sourcepub fn from_char(c: char) -> Self
pub fn from_char(c: char) -> Self
Create a new Ruby string from the Rust char c
.
The encoding of the Ruby string will be UTF-8.
§Panics
Panics if called from a non-Ruby thread. See Ruby::str_from_char
for the non-panicking version.
§Examples
use magnus::{rb_assert, RString};
let c = RString::from_char('a');
rb_assert!(r#"c == "a""#, c);
use magnus::{rb_assert, RString};
let c = RString::from_char('🦀');
rb_assert!(r#"c == "🦀""#, c);
sourcepub fn chr<T>(code: u32, enc: T) -> Result<Self, Error>where
T: Into<RbEncoding>,
pub fn chr<T>(code: u32, enc: T) -> Result<Self, 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
.
§Panics
Panics if called from a non-Ruby thread. See Ruby::chr
for the
non-panicking version.
§Examples
use magnus::{encoding::RbEncoding, rb_assert, RString};
let c = RString::chr(97, RbEncoding::usascii()).unwrap();
rb_assert!(r#"c == "a""#, c);
use magnus::{encoding::RbEncoding, rb_assert, RString};
let c = RString::chr(129408, RbEncoding::utf8()).unwrap();
rb_assert!(r#"c == "🦀""#, c);
Create a new Ruby string that shares the same backing data as s
.
Both string objects will point at the same underlying data until one is modified, and only then will the data be duplicated. This operation is cheep, and useful for cases where you may need to modify a string, but don’t want to mutate a value passed to your function.
§Examples
use magnus::{rb_assert, RString};
let s = RString::new("example");
let dup = RString::new_shared(s);
rb_assert!("s == dup", s, dup);
// mutating one doesn't mutate both
dup.cat("foo");
rb_assert!("s != dup", s, dup);
sourcepub fn new_frozen(s: Self) -> Self
pub fn new_frozen(s: Self) -> Self
Create a new Ruby string that is a frozen copy of s
.
This can be used to get a copy of a string that is guranteed not to be modified while you are referencing it.
§Examples
use magnus::{rb_assert, RString};
let orig = RString::new("example");
let frozen = RString::new_frozen(orig);
rb_assert!(r#"frozen == "example""#, frozen);
// mutating original doesn't impact the frozen copy
orig.cat("foo");
rb_assert!(r#"frozen == "example""#, frozen);
sourcepub unsafe fn as_slice(&self) -> &[u8] ⓘ
pub unsafe fn as_slice(&self) -> &[u8] ⓘ
Return self
as a slice of bytes.
§Safety
This is directly viewing memory owned and managed by Ruby. Ruby may modify or free the memory backing the returned slice, the caller must ensure this does not happen.
Ruby must not be allowed to garbage collect or modify self
while a
refrence to the slice is held.
§Examples
use magnus::RString;
let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_slice(), [101, 120, 97, 109, 112, 108, 101]) };
sourcepub unsafe fn codepoints(&self) -> Codepoints<'_> ⓘ
pub unsafe fn codepoints(&self) -> Codepoints<'_> ⓘ
Return an iterator over self
’s codepoints.
§Safety
The returned iterator references memory owned and managed by Ruby. Ruby may modify or free that memory, the caller must ensure this does not happen at any time while still holding a reference to the iterator.
§Examples
use magnus::{Error, RString};
let s = RString::new("🦀 café");
let codepoints = unsafe {
// ensure string isn't mutated during iteration by creating a
// frozen copy and iterating over that
let f = RString::new_frozen(s);
f.codepoints().collect::<Result<Vec<_>, Error>>().unwrap()
};
assert_eq!(codepoints, [129408, 32, 99, 97, 102, 233]);
sourcepub unsafe fn char_bytes(&self) -> CharBytes<'_> ⓘ
pub unsafe fn char_bytes(&self) -> CharBytes<'_> ⓘ
Return an iterator over self
’s chars as slices of bytes.
§Safety
The returned iterator references memory owned and managed by Ruby. Ruby may modify or free that memory, the caller must ensure this does not happen at any time while still holding a reference to the iterator.
§Examples
use magnus::RString;
let s = RString::new("🦀 café");
// ensure string isn't mutated during iteration by creating a frozen
// copy and iterating over that
let f = RString::new_frozen(s);
let codepoints = unsafe { f.char_bytes().collect::<Vec<_>>() };
assert_eq!(
codepoints,
[
&[240, 159, 166, 128][..],
&[32],
&[99],
&[97],
&[102],
&[195, 169]
]
);
sourcepub fn offset(self, pos: usize) -> usize
pub fn offset(self, pos: usize) -> usize
Converts a character offset to a byte offset.
§Examples
use magnus::RString;
let s = RString::new("🌊🦀🏝️");
assert_eq!(s.offset(1), 4);
assert_eq!(s.offset(2), 8);
sourcepub fn is_utf8_compatible_encoding(self) -> bool
pub fn is_utf8_compatible_encoding(self) -> bool
Returns true if the encoding for this string is UTF-8 or US-ASCII, false otherwise.
The encoding on a Ruby String is just a label, it provides no guarantee that the String really is valid UTF-8.
§Examples
use magnus::{eval, RString};
let s: RString = eval!(r#""café""#).unwrap();
assert!(s.is_utf8_compatible_encoding());
use magnus::{eval, RString};
let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
assert!(!s.is_utf8_compatible_encoding());
sourcepub fn conv_enc<T>(self, enc: T) -> Result<Self, Error>where
T: Into<RbEncoding>,
pub fn conv_enc<T>(self, enc: T) -> Result<Self, Error>where
T: Into<RbEncoding>,
Returns a new string by reencoding self
from its current encoding to
the given enc
.
§Examples
use magnus::{encoding::RbEncoding, eval, RString};
let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_slice(), &[99, 97, 102, 233]) };
let e = s.conv_enc(RbEncoding::utf8()).unwrap();
unsafe { assert_eq!(e.as_slice(), &[99, 97, 102, 195, 169]) };
sourcepub fn scrub(self, replacement: Option<Self>) -> Result<Option<Self>, Error>
pub fn scrub(self, replacement: Option<Self>) -> Result<Option<Self>, Error>
Returns a string omitting ‘broken’ parts of the string according to its encoding.
If replacement
is Some(RString)
and ‘broken’ portion will be
replaced with that string. When replacement
is None
an encoding
specific default will be used.
If self
is not ‘broken’ and no replacement was made, returns
Ok(None)
.
§Examples
use magnus::{encoding::RbEncoding, RString};
// 156 is invalid for utf-8
let s = RString::enc_new([156, 57, 57], RbEncoding::utf8());
assert_eq!(s.scrub(None).unwrap().unwrap().to_string().unwrap(), "�99");
assert_eq!(s.scrub(Some(RString::new("?"))).unwrap().unwrap().to_string().unwrap(), "?99");
assert_eq!(s.scrub(Some(RString::new(""))).unwrap().unwrap().to_string().unwrap(), "99");
sourcepub fn enc_coderange(self) -> Coderange
pub fn enc_coderange(self) -> Coderange
Returns the cached coderange value that describes how self
relates to
its encoding.
See also enc_coderange_scan
.
§Examples
use magnus::{encoding::Coderange, prelude::*, RString};
// Coderange is unknown on creation.
let s = RString::new("test");
assert_eq!(s.enc_coderange(), Coderange::Unknown);
// Methods that operate on the string using the encoding will set the
// coderange as a side effect.
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::SevenBit);
// Operations with two strings with known coderanges will set it
// appropriately.
let t = RString::new("🦀");
let _: usize = t.funcall("length", ()).unwrap();
assert_eq!(t.enc_coderange(), Coderange::Valid);
s.buf_append(t).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);
// Operations that modify the string with an unknown coderange will
// set the coderange back to unknown.
s.cat([128]);
assert_eq!(s.enc_coderange(), Coderange::Unknown);
// Which may leave the string with a broken encoding.
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Broken);
sourcepub fn enc_coderange_scan(self) -> Coderange
pub fn enc_coderange_scan(self) -> Coderange
Scans self
to establish its coderange.
If the coderange is already known, simply returns the known value.
See also enc_coderange
.
§Examples
use magnus::{encoding::Coderange, RString};
let s = RString::new("test");
assert_eq!(s.enc_coderange_scan(), Coderange::SevenBit);
sourcepub fn enc_coderange_clear(self)
pub fn enc_coderange_clear(self)
Clear self
’s cached coderange, setting it to Unknown
.
§Examples
use magnus::{encoding::Coderange, prelude::*, RString};
let s = RString::new("🦀");
// trigger setting coderange
let _: usize = s.funcall("length", ()).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);
s.enc_coderange_clear();
assert_eq!(s.enc_coderange(), Coderange::Unknown);
sourcepub unsafe fn enc_coderange_set(self, cr: Coderange)
pub unsafe fn enc_coderange_set(self, cr: Coderange)
Sets self
’s cached coderange.
Rather than using the method it is recommended to set the coderange to
Unknown
with enc_coderange_clear
and let Ruby determine the coderange lazily when needed.
§Safety
This must be set correctly. SevenBit
if all codepoints are within
0..=127, Valid
if the string is valid for its encoding, or Broken
if it is not. Unknown
can be set safely with
enc_coderange_clear
.
§Examples
use magnus::{
encoding::{self, Coderange},
exception,
prelude::*,
Error, RString,
};
fn crabbify(s: RString) -> Result<(), Error> {
if s.enc_get() != encoding::Index::utf8() {
return Err(Error::new(exception::encoding_error(), "expected utf-8"));
}
let original = s.enc_coderange();
// ::cat() will clear the coderange
s.cat("🦀");
// we added a multibyte char, so if we started with `SevenBit` it
// should be upgraded to `Valid`, and if it was `Valid` it is still
// `Valid`.
if original == Coderange::SevenBit || original == Coderange::Valid {
unsafe {
s.enc_coderange_set(Coderange::Valid);
}
}
Ok(())
}
let s = RString::new("test");
// trigger setting coderange
let _: usize = s.funcall("length", ()).unwrap();
crabbify(s).unwrap();
assert_eq!(s.enc_coderange(), Coderange::Valid);
sourcepub unsafe fn test_as_str(&self) -> Option<&str>
pub unsafe fn test_as_str(&self) -> Option<&str>
Returns a Rust &str
reference to the value of self
.
Returns None
if self
’s encoding is not UTF-8 (or US-ASCII), or if
the string is not valid UTF-8.
§Safety
This is directly viewing 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.
Ruby must not be allowed to garbage collect or modify self
while a
refrence to the str is held.
§Examples
use magnus::RString;
let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.test_as_str().unwrap(), "example") };
sourcepub unsafe fn as_str(&self) -> Result<&str, Error>
pub unsafe fn as_str(&self) -> Result<&str, Error>
Returns a Rust &str
reference to the value of self
.
Errors if self
’s encoding is not UTF-8 (or US-ASCII), or if the
string is not valid UTF-8.
§Safety
This is directly viewing 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.
Ruby must not be allowed to garbage collect or modify self
while a
refrence to the str is held.
§Examples
use magnus::RString;
let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.as_str().unwrap(), "example") };
sourcepub unsafe fn to_string_lossy(&self) -> Cow<'_, str>
pub unsafe fn to_string_lossy(&self) -> Cow<'_, str>
Returns self
as a Rust string, ignoring the Ruby encoding and
dropping any non-UTF-8 characters. If self
is valid UTF-8 this will
return a &str
reference.
§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.
Ruby must not be allowed to garbage collect or modify self
while a
refrence to the str is held.
§Examples
use magnus::RString;
let s = RString::new("example");
// safe as we don't give Ruby the chance to mess with the string while
// we hold a refrence to the slice.
unsafe { assert_eq!(s.to_string_lossy(), "example") };
sourcepub fn to_string(self) -> Result<String, Error>
pub fn to_string(self) -> Result<String, Error>
Returns self
as an owned Rust String
. The Ruby string will be
reencoded as UTF-8 if required. Errors if the string can not be encoded
as UTF-8.
§Examples
use magnus::RString;
let s = RString::new("example");
assert_eq!(s.to_string().unwrap(), "example");
sourcepub fn to_bytes(self) -> Bytes
Available on crate feature bytes
only.
pub fn to_bytes(self) -> Bytes
bytes
only.Returns self
as an owned Rust Bytes
.
§Examples
use bytes::Bytes;
use magnus::RString;
let s = RString::new("example");
assert_eq!(s.to_bytes(), Bytes::from("example"));
sourcepub fn dump(self) -> Result<Self, Error>
pub fn dump(self) -> Result<Self, Error>
Returns a quoted version of the self
.
This can be thought of as the opposite of eval
. A string returned
from dump
can be safely passed to eval
and will result in a string
with the exact same contents as the original.
§Examples
use magnus::RString;
let s = RString::new("🦀 café");
assert_eq!(
s.dump().unwrap().to_string().unwrap(),
r#""\u{1F980} caf\u00E9""#
);
sourcepub fn is_interned(self) -> bool
pub fn is_interned(self) -> bool
Returns whether self
is a frozen interned string. Interned strings
are usually string literals with the in files with the
# frozen_string_literal: true
‘magic comment’.
Interned strings won’t be garbage collected or modified, so should be
safe to store on the heap or hold a &str
refrence to. See
as_interned_str
.
§Examples
use magnus::{eval, RString};
let s: RString = eval!(
r#"
# frozen_string_literal: true
"example"
"#
)
.unwrap();
assert!(s.is_interned());
use magnus::{eval, RString};
let s: RString = eval!(r#""example""#).unwrap();
assert!(!s.is_interned());
sourcepub fn as_interned_str(self) -> Option<FString>
pub fn as_interned_str(self) -> Option<FString>
Returns Some(FString)
if self is interned, None
otherwise.
Interned strings won’t be garbage collected or modified, so should be
safe to store on the heap or hold a &str
refrence to. The FString
type returned by this function provides a way to encode this property
into the type system, and provides safe methods to access the string
as a &str
or slice.
§Examples
use magnus::{eval, RString};
let s: RString = eval!(
r#"
# frozen_string_literal: true
"example"
"#
)
.unwrap();
assert!(s.as_interned_str().is_some());
use magnus::{eval, RString};
let s: RString = eval!(r#""example""#).unwrap();
assert!(s.as_interned_str().is_none());
sourcepub fn to_interned_str(self) -> FString
Available on ruby_gte_3_0
only.
pub fn to_interned_str(self) -> FString
ruby_gte_3_0
only.sourcepub fn buf_append(self, other: Self) -> Result<(), Error>
pub fn buf_append(self, other: Self) -> Result<(), Error>
Mutate self
, adding other
to the end. Errors if self
and
other
’s encodings are not compatible.
§Examples
use magnus::RString;
let a = RString::new("foo");
let b = RString::new("bar");
a.buf_append(b).unwrap();
assert_eq!(a.to_string().unwrap(), "foobar");
sourcepub fn cat<T: AsRef<[u8]>>(self, buf: T)
pub fn cat<T: AsRef<[u8]>>(self, buf: T)
Mutate self
, adding buf
to the end.
Note: This ignore’s self
’s encoding, and may result in self
containing invalid bytes for its encoding. It’s assumed this will more
often be used with ASCII-8BIT (aka BINARY) encoded strings. See
buf_new
and from_slice
.
§Examples
use magnus::RString;
let buf = RString::buf_new(4096);
buf.cat(&[102, 111, 111]);
buf.cat("bar");
assert_eq!(buf.to_string().unwrap(), "foobar");
sourcepub fn replace(self, other: Self) -> Result<(), Error>
pub fn replace(self, other: Self) -> Result<(), Error>
Replace the contents and encoding of self
with those of other
.
§Examples
use magnus::RString;
let a = RString::new("foo");
let b = RString::new("bar");
a.replace(b).unwrap();
assert_eq!(a.to_string().unwrap(), "bar");
Modify self
to share the same backing data as other
.
Both string objects will point at the same underlying data until one is modified, and only then will the data be duplicated.
See also replace
and
new_shared
.
§Examples
use magnus::RString;
let a = RString::new("foo");
let b = RString::new("bar");
a.shared_replace(b).unwrap();
assert_eq!(a.to_string().unwrap(), "bar");
// mutating one doesn't mutate both
b.cat("foo");
assert_eq!(a.to_string().unwrap(), "bar");
sourcepub fn update(self, beg: isize, len: usize, other: Self) -> Result<(), Error>
pub fn update(self, beg: isize, len: usize, other: Self) -> Result<(), Error>
Replace a portion of self
with other
.
beg
is the offset of the portion of self
to replace. Negative
values offset from the end of the string.
len
is the length of the portion of self
to replace. It does not
need to match the length of other
, self
will be expanded or
contracted as needed to accomdate other
.
§Examples
use magnus::RString;
let s = RString::new("foo");
s.update(-1, 1, RString::new("x")).unwrap();
assert_eq!(s.to_string().unwrap(), "fox");
let s = RString::new("splat");
s.update(0, 3, RString::new("b")).unwrap();
assert_eq!(s.to_string().unwrap(), "bat");
let s = RString::new("corncob");
s.update(1, 5, RString::new("ra")).unwrap();
assert_eq!(s.to_string().unwrap(), "crab");
sourcepub fn plus(self, other: Self) -> Result<Self, Error>
pub fn plus(self, other: Self) -> Result<Self, Error>
Create a new string by appending other
to self
.
§Examples
use magnus::RString;
let a = RString::new("foo");
let b = RString::new("bar");
assert_eq!(a.plus(b).unwrap().to_string().unwrap(), "foobar");
assert_eq!(a.to_string().unwrap(), "foo");
assert_eq!(b.to_string().unwrap(), "bar");
sourcepub fn times(self, num: usize) -> Self
pub fn times(self, num: usize) -> Self
Create a new string by repeating self
num
times.
§Examples
use magnus::RString;
assert_eq!(
RString::new("foo").times(3).to_string().unwrap(),
"foofoofoo"
);
sourcepub fn drop_bytes(self, len: usize) -> Result<(), Error>
pub fn drop_bytes(self, len: usize) -> Result<(), Error>
Shrink self
by len
bytes.
§Examples
use magnus::RString;
let s = RString::new("foobar");
s.drop_bytes(3).unwrap();
assert_eq!(s.to_string().unwrap(), "bar");
sourcepub fn capacity(self) -> usize
pub fn capacity(self) -> usize
Returns the capacity of self
.
§Examples
use magnus::RString;
let s = RString::with_capacity(9);
s.cat("foo");
assert_eq!(3, s.len());
assert!(s.capacity() >= 9);
sourcepub fn is_empty(self) -> bool
pub fn is_empty(self) -> bool
Return whether self contains any characters or not.
§Examples
use magnus::RString;
let s = RString::new("");
assert!(s.is_empty());
sourcepub fn cmp(self, other: Self) -> Ordering
pub fn cmp(self, other: Self) -> Ordering
Compares self
with other
to establish an ordering.
§Examples
use std::cmp::Ordering;
use magnus::RString;
let a = RString::new("a");
let b = RString::new("b");
assert_eq!(Ordering::Less, a.cmp(b));
Note that std::cmp::Ordering
can be cast to i{8,16,32,64,size}
to
get the Ruby standard -1
/0
/+1
for comparison results.
assert_eq!(std::cmp::Ordering::Less as i64, -1);
assert_eq!(std::cmp::Ordering::Equal as i64, 0);
assert_eq!(std::cmp::Ordering::Greater as i64, 1);
sourcepub fn comparable(self, other: Self) -> bool
pub fn comparable(self, other: Self) -> bool
Returns whether there is a total order of strings in the encodings of
self
and other
.
If this function returns true
for self
and other
then the
ordering returned from cmp
for those strings is
‘correct’. If false
, while stable, the ordering may not follow
established rules.
sourcepub fn ellipsize(self, len: usize) -> Self
pub fn ellipsize(self, len: usize) -> Self
Shorten self
to len
, adding “…”.
If self
is shorter than len
the returned value will be self
.
§Examples
use magnus::RString;
let s = RString::new("foobarbaz");
assert_eq!(s.ellipsize(6).to_string().unwrap(), "foo...");
sourcepub fn split(self, delim: &str) -> RArray
pub fn split(self, delim: &str) -> RArray
Split self
around the given delimiter.
If delim
is an empty string then self
is split into characters.
If delim
is solely whitespace then self
is split around whitespace,
with leading, trailing, and runs of contiguous whitespace ignored.
Otherwise, self
is split around delim
.
§Examples
use magnus::{prelude::*, RString};
let s = RString::new(" foo bar baz ");
assert_eq!(
Vec::<String>::try_convert(s.split("").as_value()).unwrap(),
vec![" ", "f", "o", "o", " ", " ", "b", "a", "r", " ", " ", "b", "a", "z", " "]
);
assert_eq!(
Vec::<String>::try_convert(s.split(" ").as_value()).unwrap(),
vec!["foo", "bar", "baz"]
);
assert_eq!(
Vec::<String>::try_convert(s.split(" bar ").as_value()).unwrap(),
vec![" foo ", " baz "]
);
Trait Implementations§
source§impl EncodingCapable for RString
impl EncodingCapable for RString
source§impl IntoRString for RString
impl IntoRString for RString
source§impl Object for RString
impl Object for RString
source§fn define_singleton_method<M>(self, name: &str, func: M) -> Result<(), Error>where
M: Method,
fn define_singleton_method<M>(self, name: &str, func: M) -> Result<(), Error>where
M: Method,
self
’s scope. Read moresource§impl ReprValue for RString
impl ReprValue for RString
source§fn equal<T>(self, other: T) -> Result<bool, Error>where
T: ReprValue,
fn equal<T>(self, other: T) -> Result<bool, Error>where
T: ReprValue,
#==
. Read moresource§fn eql<T>(self, other: T) -> Result<bool, Error>where
T: ReprValue,
fn eql<T>(self, other: T) -> Result<bool, Error>where
T: ReprValue,
#eql?
. Read moresource§fn hash(self) -> Result<Integer, Error>
fn hash(self) -> Result<Integer, Error>
self
. Read moresource§fn to_bool(self) -> bool
fn to_bool(self) -> bool
self
to a bool
, following Ruby’s rules of false
and nil
as boolean false
and everything else boolean true
. Read moresource§fn funcall_public<M, A, T>(self, method: M, args: A) -> Result<T, Error>
fn funcall_public<M, A, T>(self, method: M, args: A) -> Result<T, Error>
source§fn block_call<M, A, R, T>(
self,
method: M,
args: A,
block: fn(_: &[Value], _: Option<Proc>) -> R
) -> Result<T, Error>
fn block_call<M, A, R, T>( self, method: M, args: A, block: fn(_: &[Value], _: Option<Proc>) -> R ) -> Result<T, Error>
source§fn respond_to<M>(self, method: M, include_private: bool) -> Result<bool, Error>where
M: IntoId,
fn respond_to<M>(self, method: M, include_private: bool) -> Result<bool, Error>where
M: IntoId,
self
responds to the given Ruby method. Read moresource§fn is_kind_of<T>(self, class: T) -> bool
fn is_kind_of<T>(self, class: T) -> bool
source§fn enumeratorize<M, A>(self, method: M, args: A) -> Enumerator ⓘwhere
M: IntoSymbol,
A: ArgList,
fn enumeratorize<M, A>(self, method: M, args: A) -> Enumerator ⓘwhere
M: IntoSymbol,
A: ArgList,
source§impl TryConvert for RString
impl TryConvert for RString
source§impl Write for RString
impl Write for RString
source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)