Prepends each string in other_strings
to self
and returns self
:
s = 'foo' s.prepend('bar', 'baz') # => "barbazfoo" s # => "barbazfoo"
Related: String#concat
.
Returns the string generated by calling crypt(3)
standard library function with str
and salt_str
, in this order, as its arguments. Please do not use this method any longer. It is legacy; provided only for backward compatibility with ruby scripts in earlier days. It is bad to use in contemporary programs for several reasons:
Behaviour of C’s crypt(3)
depends on the OS it is run. The generated string lacks data portability.
On some OSes such as Mac OS, crypt(3)
never fails (i.e. silently ends up in unexpected results).
On some OSes such as Mac OS, crypt(3)
is not thread safe.
So-called “traditional” usage of crypt(3)
is very very very weak. According to its manpage, Linux’s traditional crypt(3)
output has only 2**56 variations; too easy to brute force today. And this is the default behaviour.
In order to make things robust some OSes implement so-called “modular” usage. To go through, you have to do a complex build-up of the salt_str
parameter, by hand. Failure in generation of a proper salt string tends not to yield any errors; typos in parameters are normally not detectable.
For instance, in the following example, the second invocation of String#crypt
is wrong; it has a typo in “round=” (lacks “s”). However the call does not fail and something unexpected is generated.
"foo".crypt("$5$rounds=1000$salt$") # OK, proper usage "foo".crypt("$5$round=1000$salt$") # Typo not detected
Even in the “modular” mode, some hash functions are considered archaic and no longer recommended at all; for instance module $1$
is officially abandoned by its author: see phk.freebsd.dk/sagas/md5crypt_eol.html . For another instance module $3$
is considered completely broken: see the manpage of FreeBSD.
On some OS such as Mac OS, there is no modular mode. Yet, as written above, crypt(3)
on Mac OS never fails. This means even if you build up a proper salt string it generates a traditional DES hash anyways, and there is no way for you to be aware of.
"foo".crypt("$5$rounds=1000$salt$") # => "$5fNPQMxC5j6."
If for some reason you cannot migrate to other secure contemporary password hashing algorithms, install the string-crypt gem and require 'string/crypt'
to continue using it.
Both forms iterate through str, matching the pattern (which may be a Regexp
or a String
). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&
. If the pattern contains groups, each individual result is itself an array containing one entry per group.
a = "cruel world" a.scan(/\w+/) #=> ["cruel", "world"] a.scan(/.../) #=> ["cru", "el ", "wor"] a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
And the block form:
a.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" a.scan(/(.)(.)/) {|x,y| print y, x } print "\n"
produces:
<<cruel>> <<world>> rceu lowlr
Centers str
in width
. If width
is greater than the length of str
, returns a new String
of length width
with str
centered and padded with padstr
; otherwise, returns str
.
"hello".center(4) #=> "hello" "hello".center(20) #=> " hello " "hello".center(20, '123') #=> "1231231hello12312312"
Returns a copy of str
with the first occurrence of pattern
replaced by the second argument. The pattern
is typically a Regexp
; if given as a String
, any regular expression metacharacters it contains will be interpreted literally, e.g. \d
will match a backslash followed by ‘d’, instead of a digit.
If replacement
is a String
it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d
, where d is a group number, or \k<n>
, where n is a group name. Similarly, \&
, \'
, \`
, and +
correspond to special variables, $&
, $'
, $`
, and $+
, respectively. (See regexp.rdoc for details.) \0
is the same as \&
. \\
is interpreted as an escape, i.e., a single backslash. Note that, within replacement
the special match variables, such as $&
, will not refer to the current match.
If the second argument is a Hash
, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1
, $2
, $`
, $&
, and $'
will be set appropriately. (See regexp.rdoc for details.) The value returned by the block will be substituted for the match on each call.
"hello".sub(/[aeiou]/, '*') #=> "h*llo" "hello".sub(/([aeiou])/, '<\1>') #=> "h<e>llo" "hello".sub(/./) {|s| s.ord.to_s + ' ' } #=> "104 ello" "hello".sub(/(?<foo>[aeiou])/, '*\k<foo>*') #=> "h*e*llo" 'Is SHELL your preferred shell?'.sub(/[[:upper:]]{2,}/, ENV) #=> "Is /bin/bash your preferred shell?"
Note that a string literal consumes backslashes. (See syntax/literals.rdoc for details about string literals.) Back-references are typically preceded by an additional backslash. For example, if you want to write a back-reference \&
in replacement
with a double-quoted string literal, you need to write: "..\\&.."
. If you want to write a non-back-reference string \&
in replacement
, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&.."
. You may want to use the block form to avoid a lot of backslashes.
Returns a copy of str with all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp
; if given as a String
, any regular expression metacharacters it contains will be interpreted literally, e.g. \d
will match a backslash followed by ‘d’, instead of a digit.
If replacement
is a String
it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d
, where d is a group number, or \k<n>
, where n is a group name. Similarly, \&
, \'
, \`
, and +
correspond to special variables, $&
, $'
, $`
, and $+
, respectively. (See regexp.rdoc for details.) \0
is the same as \&
. \\
is interpreted as an escape, i.e., a single backslash. Note that, within replacement
the special match variables, such as $&
, will not refer to the current match.
If the second argument is a Hash
, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1
, $2
, $`
, $&
, and $'
will be set appropriately. (See regexp.rdoc for details.) The value returned by the block will be substituted for the match on each call.
When neither a block nor a second argument is supplied, an Enumerator
is returned.
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" "hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 " "hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}" 'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
Note that a string literal consumes backslashes. (See syntax/literals.rdoc for details on string literals.) Back-references are typically preceded by an additional backslash. For example, if you want to write a back-reference \&
in replacement
with a double-quoted string literal, you need to write: "..\\&.."
. If you want to write a non-back-reference string \&
in replacement
, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&.."
. You may want to use the block form to avoid a lot of backslashes.
Returns a new String
with the last character removed. If the string ends with \r\n
, both characters are removed. Applying chop
to an empty string returns an empty string. String#chomp
is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.
"string\r\n".chop #=> "string" "string\n\r".chop #=> "string\n" "string\n".chop #=> "string" "string".chop #=> "strin" "x".chop.chop #=> ""
Returns a new String
with the given record separator removed from the end of str (if present). If $/
has not been changed from the default Ruby record separator, then chomp
also removes carriage return characters (that is it will remove \n
, \r
, and \r\n
). If $/
is an empty string, it will remove all trailing newlines from the string.
"hello".chomp #=> "hello" "hello\n".chomp #=> "hello" "hello\r\n".chomp #=> "hello" "hello\n\r".chomp #=> "hello\n" "hello\r".chomp #=> "hello" "hello \n there".chomp #=> "hello \n there" "hello".chomp("llo") #=> "he" "hello\r\n\r\n".chomp('') #=> "hello" "hello\r\n\r\r\n".chomp('') #=> "hello\r\n\r"
Performs the same substitution as String#sub
in-place.
Returns str
if a substitution was performed or nil
if no substitution was performed.
Performs the substitutions of String#gsub
in place, returning str, or nil
if no substitutions were performed. If no block and no replacement is given, an enumerator is returned instead.
Processes str as for String#chop
, returning str, or nil
if str is the empty string. See also String#chomp!
.
Modifies str in place as described for String#chomp
, returning str, or nil
if no modifications were made.
Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count
.
"hello".delete "l","lo" #=> "heo" "hello".delete "lo" #=> "he" "hello".delete "aeiou", "^e" #=> "hell" "hello".delete "ej-m" #=> "ho"
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count
. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon" " now is the".squeeze(" ") #=> " now is the" "putters shoot balls".squeeze("m-z") #=> "puters shot balls"
Each other_str
parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str
. Any other_str
that starts with a caret ^
is negated. The sequence c1-c2
means all characters between c1 and c2. The backslash character \
can be used to escape ^
or -
and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str
.
a = "hello world" a.count "lo" #=> 5 a.count "lo", "o" #=> 2 a.count "hello", "^l" #=> 4 a.count "ej-m" #=> 4 "hello^world".count "\\^aeiou" #=> 4 "hello-world".count "a\\-eo" #=> 4 c = "hello world\\r\\n" c.count "\\" #=> 2 c.count "\\A" #=> 0 c.count "X-\\w" #=> 3
Performs a delete
operation in place, returning str, or nil
if str was not modified.
Squeezes str in place, returning either str, or nil
if no changes were made.
Returns a basic n-bit checksum of the characters in str, where n is the optional Integer
parameter, defaulting to 16. The result is simply the sum of the binary value of each byte in str modulo 2**n - 1
. This is not a particularly good checksum.
Returns the substring of self
specified by the arguments.
When the single Integer argument index
is given, returns the 1-character substring found in self
at offset index
:
'bar'[2] # => "r"
Counts backward from the end of self
if index
is negative:
'foo'[-3] # => "f"
Returns nil
if index
is out of range:
'foo'[3] # => nil 'foo'[-4] # => nil
When the two Integer arguments start
and length
are given, returns the substring of the given length
found in self
at offset start
:
'foo'[0, 2] # => "fo" 'foo'[0, 0] # => ""
Counts backward from the end of self
if start
is negative:
'foo'[-2, 2] # => "oo"
Special case: returns a new empty String if start
is equal to the length of self
:
'foo'[3, 2] # => ""
Returns nil
if start
is out of range:
'foo'[4, 2] # => nil 'foo'[-4, 2] # => nil
Returns the trailing substring of self
if length
is large:
'foo'[1, 50] # => "oo"
Returns nil
if length
is negative:
'foo'[0, -1] # => nil
When the single Range argument range
is given, derives start
and length
values from the given range
, and returns values as above:
'foo'[0..1]
is equivalent to 'foo'[0, 2]
.
'foo'[0...1]
is equivalent to 'foo'[0, 1]
.
When the Regexp argument regexp
is given, and the capture
argument is 0
, returns the first matching substring found in self
, or nil
if none found:
'foo'[/o/] # => "o" 'foo'[/x/] # => nil s = 'hello there' s[/[aeiou](.)\1/] # => "ell" s[/[aeiou](.)\1/, 0] # => "ell"
If argument capture
is given and not 0
, it should be either an Integer capture group index or a String or Symbol capture group name; the method call returns only the specified capture (see Regexp Capturing):
s = 'hello there' s[/[aeiou](.)\1/, 1] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"
If an invalid capture group index is given, nil
is returned. If an invalid capture group name is given, IndexError
is raised.
When the single String argument substring
is given, returns the substring from self
if found, otherwise nil
:
'foo'['oo'] # => "oo" 'foo'['xx'] # => nil
String#slice
is an alias for String#[]
.
Deletes the specified portion from str, and returns the portion deleted.
string = "this is a string" string.slice!(2) #=> "i" string.slice!(3..6) #=> " is " string.slice!(/s.*t/) #=> "sa st" string.slice!("r") #=> "r" string #=> "thing"
Searches sep or pattern (regexp) in the string and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.
"hello".partition("l") #=> ["he", "l", "lo"] "hello".partition("x") #=> ["hello", "", ""] "hello".partition(/.l/) #=> ["h", "el", "lo"]
Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.
"hello".rpartition("l") #=> ["hel", "l", "o"] "hello".rpartition("x") #=> ["", "", "hello"] "hello".rpartition(/.l/) #=> ["he", "ll", "o"]
The match from the end means starting at the possible last position, not the last of longest matches.
"hello".rpartition(/l+/) #=> ["hel", "l", "o"]
To partition at the last longest match, needs to combine with negative lookbehind.
"hello".rpartition(/(?<!l)l+/) #=> ["he", "ll", "o"]
Or String#partition
with negative lookforward.
"hello".partition(/l+(?!.*l)/) #=> ["he", "ll", "o"]
Returns a copied string whose encoding is ASCII-8BIT.
The first form returns a copy of str
transcoded to encoding encoding
. The second form returns a copy of str
transcoded from src_encoding to dst_encoding. The last form returns a copy of str
transcoded to Encoding.default_internal
.
By default, the first and second form raise Encoding::UndefinedConversionError
for characters that are undefined in the destination encoding, and Encoding::InvalidByteSequenceError
for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings.
The options
keyword arguments give details for conversion. The arguments are:
If the value is :replace
, encode
replaces invalid byte sequences in str
with the replacement character. The default is to raise the Encoding::InvalidByteSequenceError
exception
If the value is :replace
, encode
replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError
.
Sets the replacement string to the given value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.
Sets the replacement string by the given object for undefined character. The object should be a Hash
, a Proc
, a Method
, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.
The value must be :text
or :attr
. If the value is :text
encode
replaces undefined characters with their (upper-case hexadecimal) numeric character references. ‘&’, ‘<’, and ‘>’ are converted to “&”, “<”, and “>”, respectively. If the value is :attr
, encode
also quotes the replacement result (using ‘“’), and replaces ‘”’ with “"”.
Replaces LF (“n”) with CR (“r”) if value is true.
Replaces LF (“n”) with CRLF (“rn”) if value is true.
Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.