Strings

Strings are probably the most commonly used data type in Ruby, and they have a powerful and wide-ranging API to prove it. Here are some of the most useful and most interesting String methods.

Finding Information about a String

The length of a string is accessible with the method String#length or String#size, which are aliases of each other. The length is in characters and is determined by the current encoding. You can get the length in bytes with the method String#bytesize. The method String#empty? returns true if the length of the string is zero.

If you want to know how many times a given character is used in a string, you can use String#count(*selectors). This works, as you probably expect, if you pass in a single character, but it ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.