Results for: "String#[]"

Returns a 3-element array of substrings of self.

Matches a pattern against self, scanning backwards from the end. The pattern is:

If the pattern is matched, returns pre-match, last-match, post-match:

'hello'.rpartition('l')      # => ["hel", "l", "o"]
'hello'.rpartition('ll')     # => ["he", "ll", "o"]
'hello'.rpartition('h')      # => ["", "h", "ello"]
'hello'.rpartition('o')      # => ["hell", "o", ""]
'hello'.rpartition(/l+/)     # => ["hel", "l", "o"]
'hello'.rpartition('')       # => ["hello", "", ""]
'тест'.rpartition('т')       # => ["тес", "т", ""]
'こんにちは'.rpartition('に')  # => ["こん", "に", "ちは"]

If the pattern is not matched, returns two empty strings and a copy of self:

'hello'.rpartition('x') # => ["", "", "hello"]

Related: String#partition, String#split.

Returns a copy of self that has ASCII-8BIT encoding; the underlying bytes are not modified:

s = "\x99"
s.encoding   # => #<Encoding:UTF-8>
t = s.b      # => "\x99"
t.encoding   # => #<Encoding:ASCII-8BIT>

s = "\u4095" # => "䂕"
s.encoding   # => #<Encoding:UTF-8>
s.bytes      # => [228, 130, 149]
t = s.b      # => "\xE4\x82\x95"
t.encoding   # => #<Encoding:ASCII-8BIT>
t.bytes      # => [228, 130, 149]

Returns a frozen, possibly pre-existing copy of the string.

The returned String will be deduplicated as long as it does not have any instance variables set on it and is not a String subclass.

Note that -string variant is more convenient for defining constants:

FILENAME = -'config/database.yml'

while dedup is better suitable for using the method in chains of calculations:

@url_list.concat(urls.map(&:dedup))

Returns a copy of self transcoded as determined by dst_encoding. By default, raises an exception if self contains an invalid byte or a character not defined in dst_encoding; that behavior may be modified by encoding options; see below.

With no arguments:

With only argument dst_encoding given, uses that encoding:

s = "Ruby\x99".force_encoding('Windows-1252')
s.encoding            # => #<Encoding:Windows-1252>
t = s.encode('UTF-8') # => "Ruby™"
t.encoding            # => #<Encoding:UTF-8>

With arguments dst_encoding and src_encoding given, interprets self using src_encoding, encodes the new string using dst_encoding:

s = "Ruby\x99"
t = s.encode('UTF-8', 'Windows-1252') # => "Ruby™"
t.encoding                            # => #<Encoding:UTF-8>

Optional keyword arguments enc_opts specify encoding options; see Encoding Options.

Please note that, unless invalid: :replace option is given, conversion from an encoding enc to the same encoding enc (independent of whether enc is given explicitly or implicitly) is a no-op, i.e. the string is simply copied without any changes, and no exceptions are raised, even if there are invalid bytes.

Like encode, but applies encoding changes to self; returns self.

Returns self if self is a String, or self converted to a String if self is a subclass of String.

Changes the encoding of self to encoding, which may be a string encoding name or an Encoding object; returns self:

s = 'łał'
s.bytes                   # => [197, 130, 97, 197, 130]
s.encoding                # => #<Encoding:UTF-8>
s.force_encoding('ascii') # => "\xC5\x82a\xC5\x82"
s.encoding                # => #<Encoding:US-ASCII>

Does not change the underlying bytes:

s.bytes                   # => [197, 130, 97, 197, 130]

Makes the change even if the given encoding is invalid for self (as is the change above):

s.valid_encoding?                 # => false
s.force_encoding(Encoding::UTF_8) # => "łał"
s.valid_encoding?                 # => true

Returns true if self is encoded correctly, false otherwise:

"\xc2\xa1".force_encoding("UTF-8").valid_encoding? # => true
"\xc2".force_encoding("UTF-8").valid_encoding?     # => false
"\x80".force_encoding("UTF-8").valid_encoding?     # => false

Like String#tr, but also squeezes the modified portions of the translated string; returns a new string (translated and squeezed).

'hello'.tr_s('l', 'r')   #=> "hero"
'hello'.tr_s('el', '-')  #=> "h-o"
'hello'.tr_s('el', 'hx') #=> "hhxo"

Related: String#squeeze.

If object is a String object, returns object.

Otherwise if object responds to :to_str, calls object.to_str and returns the result.

Returns nil if object does not respond to :to_str.

Raises an exception unless object.to_str returns a String object.

Replaces the contents of self with the contents of other_string:

s = 'foo'        # => "foo"
s.replace('bar') # => "bar"

Returns an array of the grapheme clusters in self (see Unicode Grapheme Cluster Boundaries):

s = "\u0061\u0308-pqr-\u0062\u0308-xyz-\u0063\u0308" # => "ä-pqr-b̈-xyz-c̈"
s.grapheme_clusters
# => ["ä", "-", "p", "q", "r", "-", "b̈", "-", "x", "y", "z", "-", "c̈"]

Returns whether self starts with any of the given string_or_regexp.

Matches patterns against the beginning of self. For each given string_or_regexp, the pattern is:

Returns true if any pattern matches the beginning, false otherwise:

'hello'.start_with?('hell')               # => true
'hello'.start_with?(/H/i)                 # => true
'hello'.start_with?('heaven', 'hell')     # => true
'hello'.start_with?('heaven', 'paradise') # => false
'тест'.start_with?('т')                   # => true
'こんにちは'.start_with?('こ')              # => true

Related: String#end_with?.

Like String#tr_s, but modifies self in place. Returns self if any changes were made, nil otherwise.

Related: String#squeeze!.

With a block given, forms the substrings (“lines”) that are the result of splitting self at each occurrence of the given line separator line_sep; passes each line to the block; returns self:

s = <<~EOT
This is the first line.
This is line two.

This is line four.
This is line five.
EOT

s.each_line {|line| p line }

Output:

"This is the first line.\n"
"This is line two.\n"
"\n"
"This is line four.\n"
"This is line five.\n"

With a different line_sep:

s.each_line(' is ') {|line| p line }

Output:

"This is "
"the first line.\nThis is "
"line two.\n\nThis is "
"line four.\nThis is "
"line five.\n"

With chomp as true, removes the trailing line_sep from each line:

s.each_line(chomp: true) {|line| p line }

Output:

"This is the first line."
"This is line two."
""
"This is line four."
"This is line five."

With an empty string as line_sep, forms and passes “paragraphs” by splitting at each occurrence of two or more newlines:

s.each_line('') {|line| p line }

Output:

"This is the first line.\nThis is line two.\n\n"
"This is line four.\nThis is line five.\n"

With no block given, returns an enumerator.

Calls the given block with each successive codepoint from self; each codepoint is the integer value for a character; returns self:

'hello'.each_codepoint {|codepoint| print codepoint, ' ' }
print "\n"
'тест'.each_codepoint {|codepoint| print codepoint, ' ' }
print "\n"
'こんにちは'.each_codepoint {|codepoint| print codepoint, ' ' }
print "\n"

Output:

104 101 108 108 111
1090 1077 1089 1090
12371 12435 12395 12385 12399

Returns an enumerator if no block is given.

Creates a new string of the given length and yields a zero-copy IO::Buffer instance to the block which uses the string as a source. The block is expected to write to the buffer and the string will be returned.

IO::Buffer.string(4) do |buffer|
  buffer.set_string("Ruby")
end
# => "Ruby"

Returns self interpreted as a Complex object; leading whitespace and trailing garbage are ignored:

'9'.to_c                 # => (9+0i)
'2.5'.to_c               # => (2.5+0i)
'2.5/1'.to_c             # => ((5/2)+0i)
'-3/2'.to_c              # => ((-3/2)+0i)
'-i'.to_c                # => (0-1i)
'45i'.to_c               # => (0+45i)
'3-4i'.to_c              # => (3-4i)
'-4e2-4e-2i'.to_c        # => (-400.0-0.04i)
'-0.0-0.0i'.to_c         # => (-0.0-0.0i)
'1/2+3/4i'.to_c          # => ((1/2)+(3/4)*i)
'1.0@0'.to_c             # => (1+0.0i)
"1.0@#{Math::PI/2}".to_c # => (0.0+1i)
"1.0@#{Math::PI}".to_c   # => (-1+0.0i)

Returns Complex zero if the string cannot be converted:

'ruby'.to_c        # => (0+0i)

See Kernel#Complex.

Returns the result of interpreting leading characters in str as a BigDecimal.

require 'bigdecimal'
require 'bigdecimal/util'

"0.5".to_d             # => 0.5e0
"123.45e1".to_d        # => 0.12345e4
"45.67 degrees".to_d   # => 0.4567e2

See also Kernel.BigDecimal.

Returns the result of interpreting leading characters in str as a rational. Leading whitespace and extraneous characters past the end of a valid number are ignored. Digit sequences can be separated by an underscore. If there is not a valid number at the start of str, zero is returned. This method never raises an exception.

'  2  '.to_r       #=> (2/1)
'300/2'.to_r       #=> (150/1)
'-9.2'.to_r        #=> (-46/5)
'-9.2e2'.to_r      #=> (-920/1)
'1_234_567'.to_r   #=> (1234567/1)
'21 June 09'.to_r  #=> (21/1)
'21/06/09'.to_r    #=> (7/2)
'BWV 1079'.to_r    #=> (0/1)

NOTE: “0.3”.to_r isn’t the same as 0.3.to_r. The former is equivalent to “3/10”.to_r, but the latter isn’t so.

"0.3".to_r == 3/10r  #=> true
0.3.to_r   == 3/10r  #=> false

See also Kernel#Rational.

Returns the result of interpreting leading characters in self as an integer in the given base (which must be in (0, 2..36)):

'123456'.to_i     # => 123456
'123def'.to_i(16) # => 1195503

With base zero, string object may contain leading characters to specify the actual base:

'123def'.to_i(0)   # => 123
'0123def'.to_i(0)  # => 83
'0b123def'.to_i(0) # => 1
'0o123def'.to_i(0) # => 83
'0d123def'.to_i(0) # => 123
'0x123def'.to_i(0) # => 1195503

Characters past a leading valid number (in the given base) are ignored:

'12.345'.to_i   # => 12
'12345'.to_i(2) # => 1

Returns zero if there is no leading valid number:

'abcdef'.to_i # => 0
'2'.to_i(2)   # => 0

Returns the result of interpreting leading characters in self as a Float:

'3.14159'.to_f  # => 3.14159
'1.234e-2'.to_f # => 0.01234

Characters past a leading valid number (in the given base) are ignored:

'3.14 (pi to two places)'.to_f # => 3.14

Returns zero if there is no leading valid number:

'abcdef'.to_f # => 0.0

Returns self if self is a String, or self converted to a String if self is a subclass of String.

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

'cat and dog'.to_sym   #=> :"cat and dog"

Returns whether self ends with any of the given strings.

Returns true if any given string matches the end, false otherwise:

'hello'.end_with?('ello')               #=> true
'hello'.end_with?('heaven', 'ello')     #=> true
'hello'.end_with?('heaven', 'paradise') #=> false
'тест'.end_with?('т')                   # => true
'こんにちは'.end_with?('は')              # => true

Related: String#start_with?.

Search took: 4ms  ·  Total Results: 3744