Skip to content

Ruby String API

Ruby's String — a mutable sequence of bytes holding characters, with a rich set of methods.

1 class · 8 methods

String

8 methods

A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters.

String#length -> Integer

Returns the number of characters in the string.

Returns

Integer

Example

ruby
"hello".length   # 5
"日本語".length   # 3
String#upcase -> String

Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.

Returns

String

Example

ruby
"hello World".upcase  # "HELLO WORLD"
String#downcase -> String

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.

Returns

String

Example

ruby
"HELLO World".downcase  # "hello world"
String#split(pattern=nil, [limit]) -> Array

Divides str into substrings based on a delimiter, returning an array of substrings.

Parameters

NameTypeDescription
patternRegexp|String|nilDelimiter pattern. nil splits on whitespace.
limitIntegerOptional limit on number of splits.

Returns

Array

Example

ruby
"a,b,c".split(",")      # ["a", "b", "c"]
"  hello world  ".split  # ["hello", "world"]
"a-b-c".split("-", 2)    # ["a", "b-c"]
String#gsub(pattern, replacement) -> String

Returns a copy of str with all occurrences of pattern substituted with replacement.

Parameters

NameTypeDescription
patternRegexp|StringPattern to match.
replacementString|HashReplacement string or mapping.

Returns

String

Example

ruby
"hello world".gsub("o", "0")    # "hell0 w0rld"
"2024-01-01".gsub("-", "/")  # "2024/01/01"
String#strip -> String

Returns a copy of str with leading and trailing whitespace removed.

Returns

String

Example

ruby
"  hello  ".strip  # "hello"
String#include?(substring) -> bool

Returns true if str contains the given string or character.

Parameters

NameTypeDescription
substringStringSubstring to check for.

Returns

Boolean

Example

ruby
"hello world".include?("world")  # true
"hello".include?("z")            # false
String#chars -> Array

Returns an array of characters in str.

Returns

Array

Example

ruby
"hello".chars  # ["h", "e", "l", "l", "o"]