Ruby strings

Here I try to make sense of the methods of Ruby strings.

Access

  • #[]
  • #[]= (assignment)
  • #byteslice
  • #getbyte
  • #setbyte
  • #slice

Information

Encoding related:

  • #ascii_only? (true if string only has ascii characters)
  • #encoding
  • #valid_encoding? (true if string encoded correctly)

Querying size:

  • #bytesize
  • #count
  • #empty?
  • #length
  • #size

Others:

  • #inspect

Representation

Keeps information:

  • #b (Returns a copied string whose encoding is ASCII-8BIT.)
  • #bytes (returns array of bytes)
  • #chars (returns array of chars)
  • #codepoints (returns array of ordinals)
  • #dump (Produces a version of str with all non-printing characters replaced by \nnn notation and all special characters escaped.)
  • #encode
  • #encode!
  • #force_encoding

Hash-like:

  • #crypt (Applies a one-way cryptographic hash to str by invoking the standard library function crypt(3) with the given salt string.)
  • #hash
  • #sum (basic checksum)

Search and matching

Substring:

  • #start_with?
  • #end_with?
  • #include? (substring matching)

Regex:

  • #=~
  • #match
  • #scan
  • #index
  • #rindex

Comparison

  • #⇔
  • #==
  • #===
  • #casecmp (case insensitive)
  • #eql?

Iteration

  • #each_byte
  • #each_char
  • #each_codepoint
  • #each_line

Augmentation

  • #+ (concat)
  • #* (repetition)
  • #« (append)
  • #concat
  • #insert
  • #prepend

Transformation

Case manipulation:

  • #capitalize
  • #capitalize!
  • #downcase
  • #downcase!
  • #swapcase
  • #swapcase!
  • #upcase
  • #upcase!

Permutation:

  • #reverse
  • #reverse!

Treat string as element in a sequence:

  • #next
  • #next!
  • #succ
  • #succ!
  • #upto (different from above though related)

Formatting

  • #%
  • #center
  • #ljust
  • #rjust

Conversions

Type conversions:

  • #to_c
  • #to_f
  • #to_i
  • #to_r
  • #to_s
  • #to_str
  • #intern
  • #to_sym

Interpretations (there's a fine line here):

  • #chr
  • #hex
  • #oct
  • #ord
  • #unpack

Splitting

  • #lines (returns array of lines)
  • #partition (returns part before match, the match and part after match)
  • #rpartition
  • #split

Substitution

  • #gsub
  • #gsub!
  • #sub
  • #sub!
  • #tr
  • #tr!
  • #tr_s (removes duplicates in region affected by translation)
  • #tr_s!

Destruction

Trimming, simplifying strings:

  • #chomp (remove record separator from end of string)
  • #chomp!
  • #chop (remove last character)
  • #chop!
  • #lstrip
  • #lstrip!
  • #rstrip
  • #rstrip!
  • #strip (removes whitespace)
  • #strip!
  • #squeeze
  • #squeeze!

General purpose substring removal:

  • #clear
  • #delete
  • #delete!
  • #replace
  • #slice!

Others, not classified

  • ::new
  • ::try_convert
  • #initialize_copy