Results for: "slice"

Upcases the first character in self; downcases the remaining characters; returns self if any changes were made, nil otherwise:

s = 'hello World!' # => "hello World!"
s.capitalize!      # => "Hello world!"
s                  # => "Hello world!"
s.capitalize!      # => nil

The casing may be affected by the given options; see Case Mapping.

Related: String#capitalize.

Returns an array of substrings of self that are the result of splitting self at each occurrence of the given field separator field_sep.

When field_sep is $;:

When field_sep is ' ' and limit is nil, the split occurs at each sequence of whitespace:

'abc def ghi'.split(' ')         => ["abc", "def", "ghi"]
"abc \n\tdef\t\n  ghi".split(' ') # => ["abc", "def", "ghi"]
'abc  def   ghi'.split(' ')      => ["abc", "def", "ghi"]
''.split(' ')                    => []

When field_sep is a string different from ' ' and limit is nil, the split occurs at each occurrence of field_sep; trailing empty substrings are not returned:

'abracadabra'.split('ab')  => ["", "racad", "ra"]
'aaabcdaaa'.split('a')     => ["", "", "", "bcd"]
''.split('a')              => []
'3.14159'.split('1')       => ["3.", "4", "59"]
'!@#$%^$&*($)_+'.split('$') # => ["!@#", "%^", "&*(", ")_+"]
'тест'.split('т')          => ["", "ес"]
'こんにちは'.split('に')     => ["こん", "ちは"]

When field_sep is a Regexp and limit is nil, the split occurs at each occurrence of a match; trailing empty substrings are not returned:

'abracadabra'.split(/ab/) # => ["", "racad", "ra"]
'aaabcdaaa'.split(/a/)   => ["", "", "", "bcd"]
'aaabcdaaa'.split(//)    => ["a", "a", "a", "b", "c", "d", "a", "a", "a"]
'1 + 1 == 2'.split(/\W+/) # => ["1", "1", "2"]

If the Regexp contains groups, their matches are also included in the returned array:

'1:2:3'.split(/(:)()()/, 2) # => ["1", ":", "", "", "2:3"]

As seen above, if limit is nil, trailing empty substrings are not returned; the same is true if limit is zero:

'aaabcdaaa'.split('a')   => ["", "", "", "bcd"]
'aaabcdaaa'.split('a', 0) # => ["", "", "", "bcd"]

If limit is positive integer n, no more than n - 1- splits occur, so that at most n substrings are returned, and trailing empty substrings are included:

'aaabcdaaa'.split('a', 1) # => ["aaabcdaaa"]
'aaabcdaaa'.split('a', 2) # => ["", "aabcdaaa"]
'aaabcdaaa'.split('a', 5) # => ["", "", "", "bcd", "aa"]
'aaabcdaaa'.split('a', 7) # => ["", "", "", "bcd", "", "", ""]
'aaabcdaaa'.split('a', 8) # => ["", "", "", "bcd", "", "", ""]

Note that if field_sep is a Regexp containing groups, their matches are in the returned array, but do not count toward the limit.

If limit is negative, it behaves the same as if limit was nil, meaning that there is no limit, and trailing empty substrings are included:

'aaabcdaaa'.split('a', -1) # => ["", "", "", "bcd", "", "", ""]

If a block is given, it is called with each substring:

'abc def ghi'.split(' ') {|substring| p substring }

Output:

"abc"
"def"
"ghi"

Related: String#partition, String#rpartition.

Forms substrings (“lines”) of self according to the given arguments (see String#each_line for details); returns the lines in an array.

Returns a centered copy of self.

If integer argument size is greater than the size (in characters) of self, returns a new string of length size that is a copy of self, centered and padded on both ends with pad_string:

'hello'.center(10)       # => "  hello   "
'  hello'.center(10)     # => "   hello  "
'hello'.center(10, 'ab') # => "abhelloaba"
'тест'.center(10)        # => "   тест   "
'こんにちは'.center(10)    # => "  こんにちは   "

If size is not greater than the size of self, returns a copy of self:

'hello'.center(5)  # => "hello"
'hello'.center(1)  # => "hello"

Related: String#ljust, String#rjust.

Returns a 2-element array containing other converted to a Float and self:

f = 3.14                 # => 3.14
f.coerce(2)              # => [2.0, 3.14]
f.coerce(2.0)            # => [2.0, 3.14]
f.coerce(Rational(1, 2)) # => [0.5, 3.14]
f.coerce(Complex(1, 0))  # => [1.0, 3.14]

Raises an exception if a type conversion fails.

Returns the smallest number greater than or equal to self with a precision of ndigits decimal digits.

When ndigits is positive, returns a float with ndigits digits after the decimal point (as available):

f = 12345.6789
f.ceil(1) # => 12345.7
f.ceil(3) # => 12345.679
f = -12345.6789
f.ceil(1) # => -12345.6
f.ceil(3) # => -12345.678

When ndigits is non-positive, returns an integer with at least ndigits.abs trailing zeros:

f = 12345.6789
f.ceil(0)  # => 12346
f.ceil(-3) # => 13000
f = -12345.6789
f.ceil(0)  # => -12345
f.ceil(-3) # => -12000

Note that the limited precision of floating-point arithmetic may lead to surprising results:

(2.1 / 0.7).ceil  #=> 4 (!)

Related: Float#floor.

Returns a simpler approximation of the value (flt-|eps| <= result <= flt+|eps|). If the optional argument eps is not given, it will be chosen automatically.

0.3.rationalize          #=> (3/10)
1.333.rationalize        #=> (1333/1000)
1.333.rationalize(0.01)  #=> (4/3)

See also Float#to_r.

Returns the current execution stack of the fiber. start, count and end allow to select only parts of the backtrace.

def level3
  Fiber.yield
end

def level2
  level3
end

def level1
  level2
end

f = Fiber.new { level1 }

# It is empty before the fiber started
f.backtrace
#=> []

f.resume

f.backtrace
#=> ["test.rb:2:in `yield'", "test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
p f.backtrace(1) # start from the item 1
#=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'", "test.rb:13:in `block in <main>'"]
p f.backtrace(2, 2) # start from item 2, take 2
#=> ["test.rb:6:in `level2'", "test.rb:10:in `level1'"]
p f.backtrace(1..3) # take items from 1 to 3
#=> ["test.rb:2:in `level3'", "test.rb:6:in `level2'", "test.rb:10:in `level1'"]

f.resume

# It is nil after the fiber is finished
f.backtrace
#=> nil

Returns true if the fiber can still be resumed (or transferred to). After finishing execution of the fiber block this method will always return false.

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn’t empty.

Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError). Not available on all platforms.

File.link("testfile", ".testfile")   #=> 0
IO.readlines(".testfile")[0]         #=> "This is line one\n"

Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented exception on platforms that do not support symbolic links.

File.symlink("testfile", "link2test")   #=> 0

Returns the name of the file referenced by the given link. Not available on all platforms.

File.symlink("testfile", "link2test")   #=> 0
File.readlink("link2test")              #=> "testfile"

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2) system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.

See also Dir::rmdir.

Splits the given string into a directory and a file component and returns them in a two-element array. See also File::dirname and File::basename.

File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]

Returns true if filepath points to a symbolic link, false otherwise:

symlink = File.symlink('t.txt', 'symlink')
File.symlink?('symlink') # => true
File.symlink?('t.txt')   # => false

Returns true if the named file has the sticky bit set.

file_name can be an IO object.

Returns true if the named files are identical.

file_1 and file_2 can be an IO object.

open("a", "w") {}
p File.identical?("a", "a")      #=> true
p File.identical?("a", "./a")    #=> true
File.link("a", "b")
p File.identical?("a", "b")      #=> true
File.symlink("a", "c")
p File.identical?("a", "c")      #=> true
open("d", "w") {}
p File.identical?("a", "d")      #=> false

Returns the list of loaded encodings.

Encoding.list
#=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
      #<Encoding:ISO-2022-JP (dummy)>]

Encoding.find("US-ASCII")
#=> #<Encoding:US-ASCII>

Encoding.list
#=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
      #<Encoding:US-ASCII>, #<Encoding:ISO-2022-JP (dummy)>]

Returns the hash of available encoding alias and original encoding name.

Encoding.aliases
#=> {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1968"=>"US-ASCII",
      "SJIS"=>"Windows-31J", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}

Creates an infinite enumerator from any block, just called over and over. The result of the previous iteration is passed to the next one. If initial is provided, it is passed to the first iteration, and becomes the first element of the enumerator; if it is not provided, the first iteration receives nil, and its result becomes the first element of the iterator.

Raising StopIteration from the block stops an iteration.

Enumerator.produce(1, &:succ)   # => enumerator of 1, 2, 3, 4, ....

Enumerator.produce { rand(10) } # => infinite random number sequence

ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
enclosing_section = ancestors.find { |n| n.type == :section }

Using ::produce together with Enumerable methods like Enumerable#detect, Enumerable#slice_after, Enumerable#take_while can provide Enumerator-based alternatives for while and until cycles:

# Find next Tuesday
require "date"
Enumerator.produce(Date.today, &:succ).detect(&:tuesday?)

# Simple lexer:
require "strscan"
scanner = StringScanner.new("7+38/6")
PATTERN = %r{\d+|[-/+*]}
Enumerator.produce { scanner.scan(PATTERN) }.slice_after { scanner.eos? }.first
# => ["7", "+", "38", "/", "6"]

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

Returns any backtrace associated with the exception. The backtrace is an array of strings, each containing either “filename:lineNo: in ‘method”’ or “filename:lineNo.”

def a
  raise "boom"
end

def b
  a()
end

begin
  b()
rescue => detail
  print detail.backtrace.join("\n")
end

produces:

prog.rb:2:in `a'
prog.rb:6:in `b'
prog.rb:10

In the case no backtrace has been set, nil is returned

ex = StandardError.new
ex.backtrace
#=> nil

Returns true if exiting successful, false if not.

Search took: 4ms  ·  Total Results: 1118