Ruby | String byteslice Method

byteslice is a String class method in Ruby which is used for the byte reference.

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.

Note: If an offset is negative then it is counted from the end of the string.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate
# the byteslice method
     
# Taking a string and
# using the method
puts "Ruby String".byteslice(9)
puts "Methods".byteslice(2, 4)

chevron_right


Output:

n
thod

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate
# the byteslice method
     
# Taking a string and
# using the method
puts "Ruby String".byteslice(-1)
puts "Methods".byteslice(1..4)

chevron_right


Output:

g
etho


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.