A character selector is a string argument accepted by certain Ruby methods. Each of these instance methods accepts one or more character selectors:
String#tr(selector, replacements)
: returns a new string.
String#tr!(selector, replacements)
: returns self
or nil
.
String#tr_s(selector, replacements)
: returns a new string.
String#tr_s!(selector, replacements)
: returns self
or nil
.
String#count(*selectors)
: returns the count of the specified characters.
String#delete(*selectors)
: returns a new string.
String#delete!(*selectors)
: returns self
or nil
.
String#squeeze(*selectors)
: returns a new string.
String#squeeze!(*selectors)
: returns self
or nil
.
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') 'abracadabra'.delete('ab') 'abracadabra'.delete('abc') '0123456789'.delete('258') '!@#$%&*()_+'.delete('+&#') 'ÑеÑÑ'.delete('Ñ') 'ããã«ã¡ã¯'.delete('ã«')
Note that order and repetitions do not matter:
'abracadabra'.delete('dcab') 'abracadabra'.delete('aaaa')
In a character selector, these three characters get special treatment:
A leading caret ('^'
) functions as a ânotâ operator for the characters to its right:
'abracadabra'.delete('^bc') '0123456789'.delete('^852')
A hyphen ('-'
) between two other characters defines a range of characters instead of a plain string of characters:
'abracadabra'.delete('a-d') '0123456789'.delete('4-7') '!@#$%&*()_+'.delete(' -/') 'abracadabra'.delete('a-cq-t') '0123456789'.delete('67-950-23') 'abracadabra'.delete('^a-c')
A backslash ('\'
) acts as an escape for a caret, a hyphen, or another backslash:
'abracadabra^'.delete('\^bc') 'abracadabra-'.delete('a\-d') "hello\r\nworld".delete("\r") "hello\r\nworld".delete("\\r") "hello\r\nworld".delete("\\\r")
These instance methods accept multiple character selectors:
String#count(*selectors)
: returns the count of the specified characters.
String#delete(*selectors)
: returns a new string.
String#delete!(*selectors)
: returns self
or nil
.
String#squeeze(*selectors)
: returns a new string.
String#squeeze!(*selectors)
: returns self
or nil
.
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('bcd') s.delete('^abc', '^def') s.delete('^abcdef') s.delete('a-e', 'c-g') s.delete('cde')
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4