LANGUAGE » RUBY

String

Basic

To make strings immutable (recommended), add this the first line of the script:

ruby
# frozen_string_literal: true

Instantiation:

ruby
my_string = 'Taro'
interpolation = "Hello, #{name}"
my_string << 'concatenate me'

To escape # within a double-quoted string:

ruby
text = "Your ID is \##{user_id}"

String formatting:

ruby
format('%.1f', 8.199)  # Preferred
sprintf('%.1f', 8.199)

Methods

MethodDescription
lengthGet the length of string.
empty?Returns true if string is empty.
reverseReverse order of characters.
upcaseChange all characters to upper case.
downcaseChange all characters to lower case.
capitalizeCapitalize Every Word This Way.
gsubGlobal substitution.
include?Returns true if string includes substring.
splitSplit string by the specified separator.

Replace all s with th:

ruby
my_string.gsub(/s/, 'th')

Check if string includes substring:

ruby
my_string.include? 'substring'

Split string by space (default):

ruby
words_array = my_string.split(' ')