Character Selectors

Character Selector

A character selector is a string argument accepted by certain Ruby methods. Each of these instance methods accepts one or more character selectors:

A character selector identifies zero or more characters in self that are to be operands for the method.

In this section, we illustrate using method String#delete(selector), which deletes the selected characters.

In the simplest case, the characters selected are exactly those contained in the selector itself:

'abracadabra'.delete('a')   # => "brcdbr"
'abracadabra'.delete('ab')  # => "rcdr"
'abracadabra'.delete('abc') # => "rdr"
'0123456789'.delete('258')  # => "0134679"
'!@#$%&*()_+'.delete('+&#') # => "!@$%*()_"
'тест'.delete('т')          # => "ес"
'こんにちは'.delete('に')     # => "こんちは"

Note that order and repetitions do not matter:

'abracadabra'.delete('dcab') # => "rr"
'abracadabra'.delete('aaaa') # => "brcdbr"

In a character selector, these three characters get special treatment:

Multiple Character Selectors

These instance methods accept multiple character selectors:

In effect, the given selectors are formed into a single selector consisting of only those characters common to all of the given selectors.

All forms of selectors may be used, including negations, ranges, and escapes.

Each of these pairs of method calls is equivalent:

s.delete('abcde', 'dcbfg')

s.delete('^abc', '^def')

s.delete('a-e', 'c-g')