Home > Articles > Programming > Ruby

📄 Contents

  • Print
  • + Share This
This chapter is from the book

2.28 Counting Characters in Strings

The count method counts the number of occurrences of any of a set of specified characters:

s1 = "abracadabra"
a  = s1.count("c")      # 1
b  = s1.count("bdr")    # 5

The string parameter is like a simple regular expression. If it starts with a caret, the list is negated:

c = s1.count("^a")      # 6
d = s1.count("^bdr")    # 6

A hyphen indicates a range of characters:

e = s1.count("a-d")     # 9
f = s1.count("^a-d")    # 2
  • + Share This
  • 🔖 Save To Your Account