Page Content

Tutorials

Strings In Ruby: An Object-Oriented Approach To Text

Strings in Ruby

Objects of the String class are the main representation of text in Ruby. An essential data type, strings are flexible, dynamic, and malleable. A robust collection of operators and methods for operations like as substring extraction, text insertion and deletion, searching, and replacement are offered by the String class. Strings and all other values are objects in Ruby.

This is a description of Ruby’s strings and text:

Creating Strings (String Literals)

You can embed strings directly into your code in a number of ways with Ruby.

  • Single-Quoted String Literals
  • Double-Quoted String Literals
  • “Here Documents” (Heredocs)
  • Percent (%) Notation

Read more on What Are Literals In Ruby Explained With Code Examples

String Characteristics

Mutability: In Ruby, strings can be changed. In other words, once they are formed, their content can be modified. There are mutating (ending in!) and non-mutating versions of many string functions. Non-modifying versions return a new string with the changes, whereas mutating versions alter the old string precisely as it is.

Encoding: Support for multibyte characters was added in Ruby 1.9 and later versions, which required reworking the String class to recognise and manage these characters. With multibyte strings, code “just works” in most cases. Strings were handled as byte sequences (such as BINARY/ASCII-8BIT) in Ruby 1.8, and internationalisation required auxiliary libraries. These days, strings are made up of bytes and an encoding designation (such as US-ASCII or UTF-8) that describes how the bytes are translated into characters.

String Operators

A number of string manipulation operators are defined by the String class.

Concatenation (+ and <<)

  • Two strings are concatenated by the + operator, which creates a new String object.
  • By appending its second operand to its first, the << operator modifies the original string. It is an alternative to String#concat.

Repetition (*)

With an integer as its right-hand operand, the * operator creates a new string that iterates the left-hand string a certain number of times.

Comparison (==, !=, <, <=, >, >=)

  • If all characters are equal and a string has the same length, it is compared for equality (==,!=).
  • Using case-sensitive character code comparisons, relational operators (<, <=, >, >=) compare the relative order of strings.
  • Similar to <=>, String#casecmp returns -1, 0, or 1 in case-insensitive comparison.

Indexing ([]) for Accessing Characters and Substrings

  • When it comes to extracting or changing certain sections of a string, the square-bracket operator [] is incredibly versatile.
  • By using an index, you can retrieve specific characters (Ruby 1.8 returned an integer character code, while Ruby 1.9+ returned a 1-character string). The string’s end is where negative indices start counting.
  • You can use [index, length] or [range] to extract substrings.
  • You can replace or remove parts of a string with the []= operator.

sprintf-style Formatting (%)

For sprintf-style argument substitution, the String class defines a format operator % that is comparable to the printf function in C. In addition to helping with internationalization, this offers exact control over field widths and floating-point accuracy.

You can also read What Are Variables In Ruby With The Practical Code Examples

Common String Methods

The String class is rich with methods for various operations. You can use ri "String#method_name" from the command line to get information about built-in Ruby methods.

Case Manipulation

  • upcase, downcase, capitalize, swapcase transform the case of characters.
  • Their ! counterparts (upcase!, downcase!, capitalize!, swapcase!) modify the string in place.

Whitespace Management

  • strip removes leading and trailing whitespace. lstrip removes leading, rstrip removes trailing.
  • ljust, rjust, center justify a string within a field of a specified width, padding with spaces or a custom character.

Searching and Replacing

  • index(substring/pattern, [offset]) returns the index of the first occurrence. rindex searches backward.
  • include?(substring/char) checks if a string contains another string or character.
  • start_with? and end_with? check prefixes and suffixes (Ruby 1.9+).
  • sub(pattern, replacement) replaces the first occurrence of a pattern. gsub replaces all occurrences. Their ! versions modify in place. Regular expressions can be used for patterns.

Splitting and Joining

  • Using a delimiter (string or regex), split([delimiter]) divides a string into an array of substrings. Whitespace is where it splits if no delimiter is provided.
  • An optional separator can be used when joining items of an array into a string using Array#join(separator).

Conversions

  • Strings are converted into integers by to_i and to-f, respectively.
  • A string representation of another object or the string itself is returned by to_s.
  • To turn a string into a symbol, use to_sym.

Input/Output Related to Strings and Text

There are several ways to read or print text.

puts

  • Unless the string already ends with a newline, it automatically adds one after each parameter after printing it after converting them to strings.
  • An array is recursively extended if an argument contains one, and each element is written on a separate line.

print

  • It does not automatically add a newline when printing its arguments after converting them to strings. A line break can only be created by explicitly including a newline character (\n) in the string.

gets

  • Opens a file or stream or reads a line from standard input.
  • Gives back the line that was read, together with any applicable trailing newlines.
  • Returns nil at the end of the file/stream (EOF).
  • The last line read is implicitly set to the global variable $_.

StringIO

  • The stringio library offers an IO object interface to string data, enabling the treatment of strings as files. When testing or when data isn’t in a file, this is helpful.

You can also read Constants In Ruby: What They Are, It’s Scope And Access

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index