Ruby: String Operations

By Xah Lee. Date:

Substring

Substring extraction is done by appending a bracket [index,count].

#-*- coding: utf-8 -*-
# ruby

# substring
aa = "01234567"
p aa[0,2] # prints โ€œ01โ€. Start with index, then count of chars.

# negative index counts from end. -1 is last char.
p aa[-2,2] # prints โ€œ67โ€.

String Length

Length of the string is .length method.

# -*- coding: utf-8 -*-
# ruby

a="this"
p a.length # 4

String Join and Repetition

Strings can be joined by a plus sign +.

# -*- coding: utf-8 -*-
# ruby

p "this" + " that" # "this that"

String can be repeated using *.

# -*- coding: utf-8 -*-
# ruby

print "this" * 2 # thisthis

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode ๐Ÿ’Ž
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. โ€œif then elseโ€
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables