Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#grapheme_clusters

() -> ::Array[::String]
() { (::String grapheme_cluter) -> void } -> self
grapheme_clusters → array_of_grapheme_clusters

Returns an array of the grapheme clusters in self (see Unicode Grapheme Cluster Boundaries):

Example
s = "ä-pqr-b̈-xyz-c̈"
s.size                   # => 16
s.bytesize               # => 19
s.grapheme_clusters.size # => 13
s.grapheme_clusters
# => ["ä", "-", "p", "q", "r", "-", "b̈", "-", "x", "y", "z", "-", "c̈"]

Details:

Example
s = "ä"
s.grapheme_clusters             # => ["ä"]           # One grapheme cluster.
s.bytes                         # => [97, 204, 136]  # Three bytes.
s.chars                         # => ["a", "̈"]       # Two characters.
s.chars.map {|char| char.ord }  # => [97, 776]       # Their values.

Related: see Converting to Non-String.

See also #getbyte #gsub #force_encoding #gsub! also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0