Returns self
with its characters reversed:
s = 'stressed' s.reverse! # => "desserts" s # => "desserts"
Concatenates each object in objects
to self
and returns self
:
s = 'foo' s.concat('bar', 'baz') # => "foobarbaz" s # => "foobarbaz"
For each given object object
that is an Integer, the value is considered a codepoint and converted to a character before concatenation:
s = 'foo' s.concat(32, 'bar', 32, 'baz') # => "foo bar baz"
Related: String#<<
, which takes a single argument.
Concatenates object
to self
and returns self
:
s = 'foo' s << 'bar' # => "foobar" s # => "foobar"
If object
is an Integer, the value is considered a codepoint and converted to a character before concatenation:
s = 'foo' s << 33 # => "foo!"
Related: String#concat
, which takes multiple arguments.
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/ . 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 self
with only the first occurrence (not all occurrences) of the given pattern
replaced.
See Substitution Methods.
Related: String#sub!
, String#gsub
, String#gsub!
.
Returns a copy of self
with all occurrences of the given pattern
replaced.
See Substitution Methods.
Returns an Enumerator
if no replacement
and no block given.
Related: String#sub
, String#sub!
, String#gsub!
.
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"
Returns self
with only the first occurrence (not all occurrences) of the given pattern
replaced.
See Substitution Methods.
Related: String#sub
, String#gsub
, String#gsub!
.
Performs the specified substring replacement(s) on self
; returns self
if any replacement occurred, nil
otherwise.
See Substitution Methods.
Returns an Enumerator
if no replacement
and no block given.
Related: String#sub
, String#gsub
, String#sub!
.
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#[]
.
Removes the substring of self
specified by the arguments; returns the removed substring.
See String#[]
for details about the arguments that specify the substring.
A few examples:
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"]