红宝石 |字符串字节片方法
byteslice是 Ruby 中的 String 类方法,用于字节引用。
Syntax: str.byteslice
Parameters: Here, str is the specified string.
Returns:
- A substring of one byte at that position if only a single integer passed.
- A substring starting at the offset given by the first, and a length is given by the second if the two integers passed.
- A substring containing bytes at offsets given by the range if the range is passed.
- nil if the length is negative or initial offset falls outside the string or the beginning of the range is greater than the end.
注意:如果偏移量为负数,则从字符串的末尾开始计算。
示例 1:
# Ruby program to demonstrate
# the byteslice method
# Taking a string and
# using the method
puts "Ruby String".byteslice(9)
puts "Methods".byteslice(2, 4)
输出:
n
thod
示例 2:
# Ruby program to demonstrate
# the byteslice method
# Taking a string and
# using the method
puts "Ruby String".byteslice(-1)
puts "Methods".byteslice(1..4)
输出:
g
etho