Returns true
if fiber
is blocking and false
otherwise. Fiber
is non-blocking if it was created via passing blocking: false
to Fiber.new
, or via Fiber.schedule
.
Note that, even if the method returns false
, the fiber behaves differently only if Fiber.scheduler
is set in the current thread.
See the “Non-blocking fibers” section in class docs for details.
Returns a copy of the storage hash for the fiber. The method can only be called on the Fiber.current
.
Sets the storage hash for the fiber. This feature is experimental and may change in the future. The method can only be called on the Fiber.current
.
You should be careful about using this method as you may inadvertently clear important fiber-storage state. You should mostly prefer to assign specific keys in the storage using Fiber::[]=
.
You can also use Fiber.new(storage: nil)
to create a fiber with an empty storage.
Example:
while request = request_queue.pop # Reset the per-request state: Fiber.current.storage = nil handle_request(request) end
Transfer control to another fiber, resuming it from where it last stopped or starting it if it was not resumed before. The calling fiber will be suspended much like in a call to Fiber.yield
.
The fiber which receives the transfer call treats it much like a resume call. Arguments passed to transfer are treated like those passed to resume.
The two style of control passing to and from fiber (one is resume
and Fiber::yield
, another is transfer
to and from fiber) can’t be freely mixed.
If the Fiber’s lifecycle had started with transfer, it will never be able to yield or be resumed control passing, only finish or transfer back. (It still can resume other fibers that are allowed to be resumed.)
If the Fiber’s lifecycle had started with resume, it can yield or transfer to another Fiber
, but can receive control back only the way compatible with the way it was given away: if it had transferred, it only can be transferred back, and if it had yielded, it only can be resumed back. After that, it again can transfer or yield.
If those rules are broken FiberError
is raised.
For an individual Fiber
design, yield/resume is easier to use (the Fiber
just gives away control, it doesn’t need to think about who the control is given to), while transfer is more flexible for complex cases, allowing to build arbitrary graphs of Fibers dependent on each other.
Example:
manager = nil # For local var to be visible inside worker block # This fiber would be started with transfer # It can't yield, and can't be resumed worker = Fiber.new { |work| puts "Worker: starts" puts "Worker: Performed #{work.inspect}, transferring back" # Fiber.yield # this would raise FiberError: attempt to yield on a not resumed fiber # manager.resume # this would raise FiberError: attempt to resume a resumed fiber (double resume) manager.transfer(work.capitalize) } # This fiber would be started with resume # It can yield or transfer, and can be transferred # back or resumed manager = Fiber.new { puts "Manager: starts" puts "Manager: transferring 'something' to worker" result = worker.transfer('something') puts "Manager: worker returned #{result.inspect}" # worker.resume # this would raise FiberError: attempt to resume a transferring fiber Fiber.yield # this is OK, the fiber transferred from and to, now it can yield puts "Manager: finished" } puts "Starting the manager" manager.resume puts "Resuming the manager" # manager.transfer # this would raise FiberError: attempt to transfer to a yielding fiber manager.resume
produces
Starting the manager Manager: starts Manager: transferring 'something' to worker Worker: starts Worker: Performed "something", transferring back Manager: worker returned "Something" Resuming the manager Manager: finished
Returns false
if the current fiber is non-blocking. Fiber
is non-blocking if it was created via passing blocking: false
to Fiber.new
, or via Fiber.schedule
.
If the current Fiber
is blocking, the method returns 1. Future developments may allow for situations where larger integers could be returned.
Note that, even if the method returns false
, Fiber
behaves differently only if Fiber.scheduler
is set in the current thread.
See the “Non-blocking fibers” section in class docs for details.
Returns the Fiber
scheduler, that was last set for the current thread with Fiber.set_scheduler
. Returns nil
if no scheduler is set (which is the default), and non-blocking fibers’ behavior is the same as blocking. (see “Non-blocking fibers” section in class docs for details about the scheduler concept).
Closes the stream in self
, if it is open, and returns nil
; ignored if self
is already closed:
dir = Dir.new('example') dir.read # => "." dir.close # => nil dir.close # => nil dir.read # Raises IOError.
Returns the path to the current working directory:
Dir.chdir("/tmp") # => 0 Dir.pwd # => "/tmp"
Forms an array entry_names of the entry names selected by the arguments.
Argument patterns
is a string pattern or an array of string patterns; note that these are not regexps; see below.
Notes for the following examples:
'*'
is the pattern that matches any entry name except those that begin with '.'
.
We use method Array#take
to shorten returned arrays that otherwise would be very large.
With no block, returns array entry_names; example (using the simple file tree):
Dir.glob('*') # => ["config.h", "lib", "main.rb"]
With a block, calls the block with each of the entry_names and returns nil
:
Dir.glob('*') {|entry_name| puts entry_name } # => nil
Output:
config.h lib main.rb
If optional keyword argument flags
is given, the value modifies the matching; see below.
If optional keyword argument base
is given, its value specifies the base directory. Each pattern string specifies entries relative to the base directory; the default is '.'
. The base directory is not prepended to the entry names in the result:
Dir.glob(pattern, base: 'lib').take(5) # => ["abbrev.gemspec", "abbrev.rb", "base64.gemspec", "base64.rb", "benchmark.gemspec"] Dir.glob(pattern, base: 'lib/irb').take(5) # => ["cmd", "color.rb", "color_printer.rb", "completion.rb", "context.rb"]
If optional keyword sort
is given, its value specifies whether the array is to be sorted; the default is true
. Passing value false
with that keyword disables sorting (though the underlying file system may already have sorted the array).
Patterns
Each pattern string is expanded according to certain metacharacters; examples below use the Ruby file tree:
'*'
: Matches any substring in an entry name, similar in meaning to regexp /.*/mx
; may be restricted by other values in the pattern strings:
'*'
matches all entry names:
Dir.glob('*').take(3) # => ["BSDL", "CONTRIBUTING.md", "COPYING"]
'c*'
matches entry names beginning with 'c'
:
Dir.glob('c*').take(3) # => ["CONTRIBUTING.md", "COPYING", "COPYING.ja"]
'*c'
matches entry names ending with 'c'
:
Dir.glob('*c').take(3) # => ["addr2line.c", "array.c", "ast.c"]
'*c*'
matches entry names that contain 'c'
, even at the beginning or end:
Dir.glob('*c*').take(3) # => ["CONTRIBUTING.md", "COPYING", "COPYING.ja"]
Does not match Unix-like hidden entry names (“dot files”). To include those in the matched entry names, use flag IO::FNM_DOTMATCH or something like '{*,.*}'
.
'**'
: Matches entry names recursively if followed by the slash character '/'
:
Dir.glob('**/').take(3) # => ["basictest/", "benchmark/", "benchmark/gc/"]
If the string pattern contains other characters or is not followed by a slash character, it is equivalent to '*'
.
'?'
Matches any single character; similar in meaning to regexp /./
:
Dir.glob('io.?') # => ["io.c"]
'[set]'
: Matches any one character in the string set; behaves like a Regexp character class, including set negation ('[^a-z]'
):
Dir.glob('*.[a-z][a-z]').take(3) # => ["CONTRIBUTING.md", "COPYING.ja", "KNOWNBUGS.rb"]
'{abc,xyz}'
: Matches either string abc or string xyz; behaves like Regexp alternation:
Dir.glob('{LEGAL,BSDL}') # => ["LEGAL", "BSDL"]
More than two alternatives may be given.
\
: Escapes the following metacharacter.
Note that on Windows, the backslash character may not be used in a string pattern: Dir['c:\foo*']
will not work, use Dir['c:/foo*']
instead.
More examples (using the simple file tree):
# We're in the example directory. File.basename(Dir.pwd) # => "example" Dir.glob('config.?') # => ["config.h"] Dir.glob('*.[a-z][a-z]') # => ["main.rb"] Dir.glob('*.[^r]*') # => ["config.h"] Dir.glob('*.{rb,h}') # => ["main.rb", "config.h"] Dir.glob('*') # => ["config.h", "lib", "main.rb"] Dir.glob('*', File::FNM_DOTMATCH) # => [".", "config.h", "lib", "main.rb"] Dir.glob(["*.rb", "*.h"]) # => ["main.rb", "config.h"] Dir.glob('**/*.rb') => ["lib/song/karaoke.rb", "lib/song.rb", "main.rb"] Dir.glob('**/*.rb', base: 'lib') # => ["song/karaoke.rb", "song.rb"] Dir.glob('**/lib') # => ["lib"] Dir.glob('**/lib/**/*.rb') # => ["lib/song/karaoke.rb", "lib/song.rb"] Dir.glob('**/lib/*.rb') # => ["lib/song.rb"]
Flags
If optional keyword argument flags
is given (the default is zero – no flags), its value should be the bitwise OR of one or more of the constants defined in module File::Constants
.
Example:
flags = File::FNM_EXTGLOB | File::FNM_DOTMATCH
Specifying flags can extend, restrict, or otherwise modify the matching.
The flags for this method (other constants in File::Constants
do not apply):
File::FNM_DOTMATCH: specifies that entry names beginning with '.'
should be considered for matching:
Dir.glob('*').take(5) # => ["BSDL", "CONTRIBUTING.md", "COPYING", "COPYING.ja", "GPL"] Dir.glob('*', flags: File::FNM_DOTMATCH).take(5) # => [".", ".appveyor.yml", ".cirrus.yml", ".dir-locals.el", ".document"]
File::FNM_EXTGLOB: enables the pattern extension '{a,b}'
, which matches pattern a and pattern b; behaves like a regexp union (e.g., '(?:a|b)'
):
pattern = '{LEGAL,BSDL}' Dir.glob(pattern) # => ["LEGAL", "BSDL"]
File::FNM_NOESCAPE: specifies that escaping with the backslash character '\'
is disabled; the character is not an escape character.
File::FNM_PATHNAME: specifies that metacharacters '*'
and '?'
do not match directory separators.
File::FNM_SHORTNAME: specifies that patterns may match short names if they exist; Windows only.
Locks or unlocks file self
according to the given locking_constant
, a bitwise OR of the values in the table below.
Not available on all platforms.
Returns false
if File::LOCK_NB
is specified and the operation would have blocked; otherwise returns 0
.
Constant | Lock | Effect |
---|---|---|
File::LOCK_EX |
Exclusive | Only one process may hold an exclusive lock for self at a time. |
File::LOCK_NB |
Non-blocking | No blocking; may be combined with File::LOCK_SH or File::LOCK_EX using the bitwise OR operator | . |
File::LOCK_SH |
Shared | Multiple processes may each hold a shared lock for self at the same time. |
File::LOCK_UN |
Unlock | Remove an existing lock held by this process. |
Example:
# Update a counter using an exclusive lock. # Don't use File::WRONLY because it truncates the file. File.open('counter', File::RDWR | File::CREAT, 0644) do |f| f.flock(File::LOCK_EX) value = f.read.to_i + 1 f.rewind f.write("#{value}\n") f.flush f.truncate(f.pos) end # Read the counter using a shared lock. File.open('counter', 'r') do |f| f.flock(File::LOCK_SH) f.read end
Returns true
if the named file exists and has a zero size.
file_name can be an IO
object.
Returns true
if filepath
points to a block device, false
otherwise:
File.blockdev?('/dev/sda1') # => true File.blockdev?(File.new('t.tmp')) # => false
Returns a Digest
subclass by name
in a thread-safe manner even when on-demand loading is involved.
require 'digest' Digest("MD5") # => Digest::MD5 Digest(:SHA256) # => Digest::SHA256 Digest(:Foo) # => LoadError: library not found for class Digest::Foo -- digest/foo
Return the receiver associated with this KeyError
exception.
Return the receiver associated with this NameError
exception.
Return the receiver associated with this FrozenError
exception.
Return this SystemCallError’s error number.
Registers _filename_ to be loaded (using Kernel::require) the first time that _const_ (which may be a String or a symbol) is accessed in the namespace of _mod_. module A end A.autoload(:B, "b") A::B.doit # autoloads "b"
If const in mod is defined as autoload, the file name to be loaded is replaced with filename. If const is defined but not as autoload, does nothing.
Returns filename to be loaded if name is registered as autoload
in the namespace of mod or one of its ancestors.
module A end A.autoload(:B, "b") A.autoload?(:B) #=> "b"
If inherit
is false, the lookup only checks the autoloads in the receiver:
class A autoload :CONST, "const.rb" end class B < A end B.autoload?(:CONST) #=> "const.rb", found in A (ancestor) B.autoload?(:CONST, false) #=> nil, not found in B itself
This method is an alias for http_header
, when HTML5
tag maker is inactive.
NOTE: use http_header
to create HTTP header blocks, this alias is only provided for backwards compatibility.
Using header
with the HTML5
tag maker will create a <header> element.
Returns a new Date object constructed from the arguments.
Argument cwyear
gives the year, and should be an integer.
Argument cweek
gives the index of the week within the year, and should be in range (1..53) or (-53..-1); in some years, 53 or -53 will be out-of-range; if negative, counts backward from the end of the year:
Date.commercial(2022, 1, 1).to_s # => "2022-01-03" Date.commercial(2022, 52, 1).to_s # => "2022-12-26"
Argument cwday
gives the indes of the weekday within the week, and should be in range (1..7) or (-7..-1); 1 or -7 is Monday; if negative, counts backward from the end of the week:
Date.commercial(2022, 1, 1).to_s # => "2022-01-03" Date.commercial(2022, 1, -7).to_s # => "2022-01-03"
When cweek
is 1:
If January 1 is a Friday, Saturday, or Sunday, the first week begins in the week after:
Date::ABBR_DAYNAMES[Date.new(2023, 1, 1).wday] # => "Sun" Date.commercial(2023, 1, 1).to_s # => "2023-01-02" Date.commercial(2023, 1, 7).to_s # => "2023-01-08"
Otherwise, the first week is the week of January 1, which may mean some of the days fall on the year before:
Date::ABBR_DAYNAMES[Date.new(2020, 1, 1).wday] # => "Wed" Date.commercial(2020, 1, 1).to_s # => "2019-12-30" Date.commercial(2020, 1, 7).to_s # => "2020-01-05"
See argument start.
Related: Date.jd
, Date.new
, Date.ordinal
.
Creates a DateTime
object denoting the given week date.
DateTime.commercial(2001) #=> #<DateTime: 2001-01-01T00:00:00+00:00 ...> DateTime.commercial(2002) #=> #<DateTime: 2001-12-31T00:00:00+00:00 ...> DateTime.commercial(2001,5,6,4,5,6,'+7') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
Like Time.utc
, except that the returned Time
object has the local timezone, not the UTC timezone:
# With seven arguments. Time.local(0, 1, 2, 3, 4, 5, 6) # => 0000-01-02 03:04:05.000006 -0600 # With exactly ten arguments. Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # => 0005-04-03 02:01:00 -0600
With no argument given:
Returns self
if self
is a local time.
Otherwise returns a new Time
in the user’s local timezone:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC t.localtime # => 2000-01-01 14:15:01 -0600
With argument zone
given, returns the new Time
object created by converting self
to the given time zone:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
For forms of argument zone
, see Timezone Specifiers.