Terminates thr
and schedules another thread to be run, returning the terminated Thread
. If this is the main thread, or the last thread, exits the process.
Return the parameters definition of the method or block that the current hook belongs to. Format is the same as for Method#parameters
Returns (and assigns to $_
) the next line from the list of files in ARGV
(or $*
), or from standard input if no files are present on the command line. Returns nil
at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil
reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV
, gets(nil)
will read the contents one file at a time.
ARGV << "testfile" print while gets
produces:
This is line one This is line two This is line three And so on...
The style of programming using $_
as an implicit parameter is gradually losing favor in the Ruby community.
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. clone
copies the frozen value state of obj, unless the :freeze
keyword argument is given with a false or true value. See also the discussion under Object#dup
.
class Klass attr_accessor :str end s1 = Klass.new #=> #<Klass:0x401b3a38> s1.str = "Hello" #=> "Hello" s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello"> s2.str[1,4] = "i" #=> "i" s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">" s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy
method of the class.
Returns arg converted to a float. Numeric
types are converted directly, and with exception to String
and nil
the rest are converted using arg.to_f
. Converting a String
with invalid characters will result in a ArgumentError
. Converting nil
generates a TypeError
. Exceptions can be suppressed by passing exception: false
.
Float(1) #=> 1.0 Float("123.456") #=> 123.456 Float("123.0_badstring") #=> ArgumentError: invalid value for Float(): "123.0_badstring" Float(nil) #=> TypeError: can't convert nil into Float Float("123.0_badstring", exception: false) #=> nil
Use Kernel#gem
to activate a specific version of gem_name
.
requirements
is a list of version requirements that the specified gem must match, most commonly “= example.version.number”. See Gem::Requirement
for how to specify a version requirement.
If you will be activating the latest version of a gem, there is no need to call Kernel#gem
, Kernel#require
will do the right thing for you.
Kernel#gem
returns true if the gem was activated, otherwise false. If the gem could not be found, didn’t match the version requirements, or a different version was already activated, an exception will be raised.
Kernel#gem
should be called before any require statements (otherwise RubyGems may load a conflicting library version).
Kernel#gem
only loads prerelease versions when prerelease requirements
are given:
gem 'rake', '>= 1.1.a', '< 2'
In older RubyGems versions, the environment variable GEM_SKIP could be used to skip activation of specified gems, for example to test out changes that haven’t been installed yet. Now RubyGems defers to -I and the RUBYLIB environment variable to skip activation of a gem.
Example:
GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
Loads and executes the Ruby program in the file filename.
If the filename is an absolute path (e.g. starts with ‘/’), the file will be loaded directly using the absolute path.
If the filename is an explicit relative path (e.g. starts with ‘./’ or ‘../’), the file will be loaded using the relative path from the current directory.
Otherwise, the file will be searched for in the library directories listed in $LOAD_PATH
($:
). If the file is found in a directory, it will attempt to load the file relative to that directory. If the file is not found in any of the directories in $LOAD_PATH
, the file will be loaded using the relative path from the current directory.
If the file doesn’t exist when there is an attempt to load it, a LoadError
will be raised.
If the optional wrap parameter is true
, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. If the optional wrap parameter is a module, the loaded script will be executed under the given module. In no circumstance will any local variables in the loaded file be propagated to the loading environment.
Registers _filename_ to be loaded (using Kernel::require) the first time that _const_ (which may be a String or a symbol) is accessed. autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
If const 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
.
autoload(:B, "b") autoload?(:B) #=> "b"
Returns the current execution stack—an array containing strings in the form file:line
or file:line: in `method'
.
The optional start parameter determines the number of initial stack entries to omit from the top of the stack.
A second optional length
parameter can be used to limit how many entries are returned from the stack.
Returns nil
if start is greater than the size of current execution stack.
Optionally you can pass a range, which will return an array containing the entries within the specified range.
def a(skip) caller(skip) end def b(skip) a(skip) end def c(skip) b(skip) end c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"] c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"] c(2) #=> ["prog:8:in `c'", "prog:12:in `<main>'"] c(3) #=> ["prog:13:in `<main>'"] c(4) #=> [] c(5) #=> nil
Deprecated. Use block_given? instead.
Repeatedly executes the block.
If no block is given, an enumerator is returned instead.
loop do print "Input: " line = gets break if !line or line =~ /^q/i # ... end
StopIteration
raised in the block breaks the loop. In this case, loop returns the “result” value stored in the exception.
enum = Enumerator.new { |y| y << "one" y << "two" :ok } result = loop { puts enum.next } #=> :ok
Returns an array containing elements selected by the block.
With a block given, calls the block with successive elements; returns an array of those elements for which the block returns a truthy value:
(0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9] a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') } a # => {:bar=>1, :baz=>2}
With no block given, returns an Enumerator.
Related: reject
.
Returns whether for any element object == element
:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?('2') # => false %w[a b c d].include?('b') # => true %w[a b c d].include?('2') # => false {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true {foo: 0, bar: 1, baz: 2}.include?('foo') # => false {foo: 0, bar: 1, baz: 2}.include?(0) # => false
Enumerable#member?
is an alias for Enumerable#include?
.
Returns the /etc/passwd
information for the user with the given integer uid
.
The information is returned as a Passwd
struct.
If uid
is omitted, the value from Passwd[:uid]
is returned instead.
See the unix manpage for getpwuid(3)
for more detail.
Etc.getpwuid(0) #=> #<struct Etc::Passwd name="root", passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
Returns the /etc/passwd
information for the user with specified login name
.
The information is returned as a Passwd
struct.
See the unix manpage for getpwnam(3)
for more detail.
Etc.getpwnam('root') #=> #<struct Etc::Passwd name="root", passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
Returns an entry from the /etc/passwd
file.
The first time it is called it opens the file and returns the first entry; each successive call returns the next entry, or nil
if the end of the file has been reached.
To close the file when processing is complete, call ::endpwent
.
Each entry is returned as a Passwd
struct.
Returns information about the group with specified integer group_id
, as found in /etc/group
.
The information is returned as a Group
struct.
See the unix manpage for getgrgid(3)
for more detail.
Etc.getgrgid(100) #=> #<struct Etc::Group name="users", passwd="x", gid=100, mem=["meta", "root"]>
Returns information about the group with specified name
, as found in /etc/group
.
The information is returned as a Group
struct.
See the unix manpage for getgrnam(3)
for more detail.
Etc.getgrnam('users') #=> #<struct Etc::Group name="users", passwd="x", gid=100, mem=["meta", "root"]>
Returns an entry from the /etc/group
file.
The first time it is called it opens the file and returns the first entry; each successive call returns the next entry, or nil
if the end of the file has been reached.
To close the file when processing is complete, call ::endgrent
.
Each entry is returned as a Group
struct
Allocate size
bytes of memory and return the integer memory address for the allocated memory.
Change the size of the memory allocated at the memory location addr
to size
bytes. Returns the memory address of the reallocated memory, which may be different than the address passed in.
Creates a new handler that opens library
, and returns an instance of Fiddle::Handle
.
If nil
is given for the library
, Fiddle::Handle::DEFAULT is used, which is the equivalent to RTLD_DEFAULT. See man 3 dlopen
for more.
lib = Fiddle.dlopen(nil)
The default is dependent on OS, and provide a handle for all libraries already loaded. For example, in most cases you can use this to access libc
functions, or ruby functions like rb_str_new
.
See Fiddle::Handle.new
for more.
Creates a new handler that opens library
, and returns an instance of Fiddle::Handle
.
If nil
is given for the library
, Fiddle::Handle::DEFAULT is used, which is the equivalent to RTLD_DEFAULT. See man 3 dlopen
for more.
lib = Fiddle.dlopen(nil)
The default is dependent on OS, and provide a handle for all libraries already loaded. For example, in most cases you can use this to access libc
functions, or ruby functions like rb_str_new
.
See Fiddle::Handle.new
for more.
Returns the Ruby objects created by parsing the given source
.
Argument source
must be, or be convertible to, a String:
If source
responds to instance method to_str
, source.to_str
becomes the source.
If source
responds to instance method to_io
, source.to_io.read
becomes the source.
If source
responds to instance method read
, source.read
becomes the source.
If both of the following are true, source becomes the String 'null'
:
Option allow_blank
specifies a truthy value.
The source, as defined above, is nil
or the empty String ''
.
Otherwise, source
remains the source.
Argument proc
, if given, must be a Proc that accepts one argument. It will be called recursively with each result (depth-first order). See details below. BEWARE: This method is meant to serialise data from trusted user input, like from your own database server or clients under your control, it could be dangerous to allow untrusted users to pass JSON
sources into it.
Argument opts
, if given, contains a Hash of options for the parsing. See Parsing Options. The default options can be changed via method JSON.load_default_options=
.
When no proc
is given, modifies source
as above and returns the result of parse(source, opts)
; see parse
.
Source for following examples:
source = <<-EOT { "name": "Dave", "age" :40, "hats": [ "Cattleman's", "Panama", "Tophat" ] } EOT
Load a String:
ruby = JSON.load(source) ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
Load an IO object:
require 'stringio' object = JSON.load(StringIO.new(source)) object # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
Load a File object:
path = 't.json' File.write(path, source) File.open(path) do |file| JSON.load(file) end # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
When proc
is given:
Modifies source
as above.
Gets the result
from calling parse(source, opts)
.
Recursively calls proc(result)
.
Returns the final result.
Example:
require 'json' # Some classes for the example. class Base def initialize(attributes) @attributes = attributes end end class User < Base; end class Account < Base; end class Admin < Base; end # The JSON source. json = <<-EOF { "users": [ {"type": "User", "username": "jane", "email": "jane@example.com"}, {"type": "User", "username": "john", "email": "john@example.com"} ], "accounts": [ {"account": {"type": "Account", "paid": true, "account_id": "1234"}}, {"account": {"type": "Account", "paid": false, "account_id": "1235"}} ], "admins": {"type": "Admin", "password": "0wn3d"} } EOF # Deserializer method. def deserialize_obj(obj, safe_types = %w(User Account Admin)) type = obj.is_a?(Hash) && obj["type"] safe_types.include?(type) ? Object.const_get(type).new(obj) : obj end # Call to JSON.load ruby = JSON.load(json, proc {|obj| case obj when Hash obj.each {|k, v| obj[k] = deserialize_obj v } when Array obj.map! {|v| deserialize_obj v } end }) pp ruby
Output:
{"users"=> [#<User:0x00000000064c4c98 @attributes= {"type"=>"User", "username"=>"jane", "email"=>"jane@example.com"}>, #<User:0x00000000064c4bd0 @attributes= {"type"=>"User", "username"=>"john", "email"=>"john@example.com"}>], "accounts"=> [{"account"=> #<Account:0x00000000064c4928 @attributes={"type"=>"Account", "paid"=>true, "account_id"=>"1234"}>}, {"account"=> #<Account:0x00000000064c4680 @attributes={"type"=>"Account", "paid"=>false, "account_id"=>"1235"}>}], "admins"=> #<Admin:0x00000000064c41f8 @attributes={"type"=>"Admin", "password"=>"0wn3d"}>}