Mixin module that provides the following:
Access to the CGI
environment variables as methods. See documentation to the CGI
class for a list of these variables. The methods are exposed by removing the leading HTTP_
(if it exists) and downcasing the name. For example, auth_type
will return the environment variable AUTH_TYPE
, and accept
will return the value for HTTP_ACCEPT
.
Access to cookies, including the cookies attribute.
Access to parameters, including the params attribute, and overloading []
to perform parameter value lookup by key.
The initialize_query
method, for initializing the above mechanisms, handling multipart forms, and allowing the class to be used in “offline” mode.
This is a set of entity constants – the ones defined in the XML
specification. These are gt
, lt
, amp
, quot
and apos
. CAUTION: these entities does not have parent and document
Utility methods for using the RubyGems API.
! –
\private Initializes the world of objects and classes. At first, the function bootstraps the class hierarchy. It initializes the most fundamental classes and their metaclasses. - \c BasicObject - \c Object - \c Module - \c Class After the bootstrap step, the class hierarchy becomes as the following diagram. \image html boottime-classes.png Then, the function defines classes, modules and methods as usual. \ingroup class
++
DateTime
A subclass of Date
that easily handles date, hour, minute, second, and offset.
DateTime
does not consider any leap seconds, does not track any summer time rules.
A DateTime
object is created with DateTime::new
, DateTime::jd
, DateTime::ordinal
, DateTime::commercial
, DateTime::parse
, DateTime::strptime
, DateTime::now
, Time#to_datetime
, etc.
require 'date' DateTime.new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>
The last element of day, hour, minute, or second can be a fractional number. The fractional number’s precision is assumed at most nanosecond.
DateTime.new(2001,2,3.5) #=> #<DateTime: 2001-02-03T12:00:00+00:00 ...>
An optional argument, the offset, indicates the difference between the local time and UTC. For example, Rational(3,24)
represents ahead of 3 hours of UTC, Rational(-5,24)
represents behind of 5 hours of UTC. The offset should be -1 to +1, and its precision is assumed at most second. The default value is zero (equals to UTC).
DateTime.new(2001,2,3,4,5,6,Rational(3,24)) #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
The offset also accepts string form:
DateTime.new(2001,2,3,4,5,6,'+03:00') #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
An optional argument, the day of calendar reform (start
), denotes a Julian day number, which should be 2298874 to 2426355 or negative/positive infinity. The default value is Date::ITALY
(2299161=1582-10-15).
A DateTime
object has various methods. See each reference.
d = DateTime.parse('3rd Feb 2001 04:05:06+03:30') #=> #<DateTime: 2001-02-03T04:05:06+03:30 ...> d.hour #=> 4 d.min #=> 5 d.sec #=> 6 d.offset #=> (7/48) d.zone #=> "+03:30" d += Rational('1.5') #=> #<DateTime: 2001-02-04%16:05:06+03:30 ...> d = d.new_offset('+09:00') #=> #<DateTime: 2001-02-04%21:35:06+09:00 ...> d.strftime('%I:%M:%S %p') #=> "09:35:06 PM" d > DateTime.new(1999) #=> true
DateTime
and when should you use Time
? It’s a common misconception that William Shakespeare and Miguel de Cervantes died on the same day in history - so much so that UNESCO named April 23 as World Book Day because of this fact. However, because England hadn’t yet adopted the Gregorian Calendar Reform (and wouldn’t until 1752) their deaths are actually 10 days apart. Since Ruby’s Time
class implements a proleptic Gregorian calendar and has no concept of calendar reform there’s no way to express this with Time
objects. This is where DateTime
steps in:
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1616 00:00:00 +0000 cervantes = DateTime.iso8601('1616-04-23', Date::ITALY) #=> Sat, 23 Apr 1616 00:00:00 +0000
Already you can see something is weird - the days of the week are different. Taking this further:
cervantes == shakespeare #=> false (shakespeare - cervantes).to_i #=> 10
This shows that in fact they died 10 days apart (in reality 11 days since Cervantes died a day earlier but was buried on the 23rd). We can see the actual date of Shakespeare’s death by using the gregorian
method to convert it:
shakespeare.gregorian #=> Tue, 03 May 1616 00:00:00 +0000
So there’s an argument that all the celebrations that take place on the 23rd April in Stratford-upon-Avon are actually the wrong date since England is now using the Gregorian calendar. You can see why when we transition across the reform date boundary:
# start off with the anniversary of Shakespeare's birth in 1751 shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1751 00:00:00 +0000 # add 366 days since 1752 is a leap year and April 23 is after February 29 shakespeare + 366 #=> Thu, 23 Apr 1752 00:00:00 +0000 # add another 365 days to take us to the anniversary in 1753 shakespeare + 366 + 365 #=> Fri, 04 May 1753 00:00:00 +0000
As you can see, if we’re accurately tracking the number of solar years since Shakespeare’s birthday then the correct anniversary date would be the 4th May and not the 23rd April.
So when should you use DateTime
in Ruby and when should you use Time
? Almost certainly you’ll want to use Time
since your app is probably dealing with current dates and times. However, if you need to deal with dates and times in a historical context you’ll want to use DateTime
to avoid making the same mistakes as UNESCO. If you also have to deal with timezones then best of luck - just bear in mind that you’ll probably be dealing with local solar times, since it wasn’t until the 19th century that the introduction of the railways necessitated the need for Standard Time and eventually timezones.
Time
is an abstraction of dates and times. Time
is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC. Also see the library module Date
. The Time
class treats GMT (Greenwich Mean Time
) and UTC (Coordinated Universal Time
) as equivalent. GMT is the older way of referring to these baseline times but persists in the names of calls on POSIX systems.
All times may have fraction. Be aware of this fact when comparing times with each other – times that are apparently equal when displayed may be different when compared.
Since Ruby 1.9.2, Time
implementation uses a signed 63 bit integer, Bignum or Rational
. The integer is a number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum or Rational
is used (before 1823, after 2116, under nanosecond), Time
works slower as when integer is used.
All of these examples were done using the EST timezone which is GMT-5.
Time
instance You can create a new instance of Time
with Time::new
. This will use the current system time. Time::now
is an alias for this. You can also pass parts of the time to Time::new
such as year, month, minute, etc. When you want to construct a time this way you must pass at least a year. If you pass the year with nothing else time will default to January 1 of that year at 00:00:00 with the current system timezone. Here are some examples:
Time.new(2002) #=> 2002-01-01 00:00:00 -0500 Time.new(2002, 10) #=> 2002-10-01 00:00:00 -0500 Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500
You can pass a UTC offset:
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
Or a timezone object:
tz = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, tz) #=> 2002-10-31 02:02:02 +0200
You can also use Time::gm
, Time::local
and Time::utc
to infer GMT, local and UTC timezones instead of using the current system setting.
You can also create a new time using Time::at
which takes the number of seconds (or fraction of seconds) since the Unix Epoch.
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Time
Once you have an instance of Time
there is a multitude of things you can do with it. Below are some examples. For all of the following examples, we will work on the assumption that you have done the following:
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
Was that a monday?
t.monday? #=> false
What year was that again?
t.year #=> 1993
Was it daylight savings at the time?
t.dst? #=> false
What’s the day a year later?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
How many seconds was that since the Unix Epoch?
t.to_i #=> 730522800
You can also do standard functions like compare two times.
t1 = Time.new(2010) t2 = Time.new(2011) t1 == t2 #=> false t1 == t1 #=> true t1 < t2 #=> true t1 > t2 #=> false Time.new(2010,10,31).between?(t1, t2) #=> true
A timezone argument must have local_to_utc
and utc_to_local
methods, and may have name
and abbr
methods.
The local_to_utc
method should convert a Time-like object from the timezone to UTC, and utc_to_local
is the opposite. The result also should be a Time
or Time-like object (not necessary to be the same class). The zone
of the result is just ignored. Time-like argument to these methods is similar to a Time
object in UTC without sub-second; it has attribute readers for the parts, e.g. year
, month
, and so on, and epoch time readers, to_i
. The sub-second attributes are fixed as 0, and utc_offset
, zone
, isdst
, and their aliases are same as a Time
object in UTC. Also to_time
, +
, and -
methods are defined.
The name
method is used for marshaling. If this method is not defined on a timezone object, Time
objects using that timezone object can not be dumped by Marshal
.
The abbr
method is used by ‘%Z’ in strftime
.
At loading marshaled data, a timezone name will be converted to a timezone object by find_timezone
class method, if the method is defined.
Similary, that class method will be called when a timezone argument does not have the necessary methods mentioned above.
A Struct
is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.
The Struct
class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor
.
Customer = Struct.new(:name, :address) do def greeting "Hello #{name}!" end end dave = Customer.new("Dave", "123 Main") dave.name #=> "Dave" dave.greeting #=> "Hello Dave!"
See Struct::new
for further examples of creating struct subclasses and instances.
In the method descriptions that follow, a “member” parameter refers to a struct member which is either a quoted string ("name"
) or a Symbol
(:name
).
Expect library adds the IO
instance method expect
, which does similar act to tcl’s expect extension.
In order to use this method, you must require expect:
require 'expect'
Please see expect
for usage.
The IO
class is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.
Many of the examples in this section use the File
class, the only standard subclass of IO
. The two classes are closely associated. Like the File
class, the Socket
library subclasses from IO
(such as TCPSocket
or UDPSocket
).
The Kernel#open
method can create an IO
(or File
) object for these types of arguments:
A plain string represents a filename suitable for the underlying operating system.
A string starting with "|"
indicates a subprocess. The remainder of the string following the "|"
is invoked as a process with appropriate input/output channels connected to it.
A string equal to "|-"
will create another Ruby instance as a subprocess.
The IO
may be opened with different file modes (read-only, write-only) and encodings for proper conversion. See IO.new
for these options. See Kernel#open
for details of the various command formats described above.
IO.popen
, the Open3
library, or Process#spawn may also be used to communicate with subprocesses through an IO
.
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb"
will be opened as "\gumby\ruby\test.rb"
. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"C:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.
The global constant ARGF
(also accessible as $<
) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF#path
and its alias ARGF#filename
are provided to access the name of the file currently being read.
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console
or the standard input/output/error IO
objects.
Requiring io/console adds the following methods:
Example:
require 'io/console' rows, columns = $stdout.winsize puts "Your screen is #{columns} wide and #{rows} tall"
An OpenStruct
is a data structure, similar to a Hash
, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.
require "ostruct" person = OpenStruct.new person.name = "John Smith" person.age = 70 person.name # => "John Smith" person.age # => 70 person.address # => nil
An OpenStruct
employs a Hash
internally to store the attributes and values and can even be initialized with one:
australia = OpenStruct.new(:country => "Australia", :capital => "Canberra") # => #<OpenStruct country="Australia", capital="Canberra">
Hash
keys with spaces or characters that could normally not be used for method calls (e.g. ()[]*
) will not be immediately available on the OpenStruct
object as a method for retrieval or assignment, but can still be reached through the Object#send
method.
measurements = OpenStruct.new("length (in inches)" => 24) measurements.send("length (in inches)") # => 24 message = OpenStruct.new(:queued? => true) message.queued? # => true message.send("queued?=", false) message.queued? # => false
Removing the presence of an attribute requires the execution of the delete_field
method as setting the property value to nil
will not remove the attribute.
first_pet = OpenStruct.new(:name => "Rowdy", :owner => "John Smith") second_pet = OpenStruct.new(:name => "Rowdy") first_pet.owner = nil first_pet # => #<OpenStruct name="Rowdy", owner=nil> first_pet == second_pet # => false first_pet.delete_field(:owner) first_pet # => #<OpenStruct name="Rowdy"> first_pet == second_pet # => true
An OpenStruct
utilizes Ruby’s method lookup structure to find and define the necessary methods for properties. This is accomplished through the methods method_missing and define_singleton_method.
This should be a consideration if there is a concern about the performance of the objects that are created, as there is much more overhead in the setting of these properties compared to using a Hash
or a Struct
.
UNIXServer
represents a UNIX domain stream server socket.
UNIXSocket
represents a UNIX domain stream client socket.
Pseudo I/O on String
object.
Commonly used to simulate ‘$stdio` or `$stderr`
require 'stringio' io = StringIO.new io.puts "Hello World" io.string #=> "Hello World\n"
BasicObject
is the parent class of all classes in Ruby. It’s an explicit blank class.
BasicObject
can be used for creating object hierarchies independent of Ruby’s object hierarchy, proxy objects like the Delegator
class, or other uses where namespace pollution from Ruby’s methods and classes must be avoided.
To avoid polluting BasicObject
for other users an appropriately named subclass of BasicObject
should be created instead of directly modifying BasicObject:
class MyObjectSystem < BasicObject end
BasicObject
does not include Kernel
(for methods like puts
) and BasicObject
is outside of the namespace of the standard library so common classes will not be found without using a full class path.
A variety of strategies can be used to provide useful portions of the standard library to subclasses of BasicObject
. A subclass could include Kernel
to obtain puts
, exit
, etc. A custom Kernel-like module could be created and included or delegation can be used via method_missing
:
class MyObjectSystem < BasicObject DELEGATE = [:puts, :p] def method_missing(name, *args, &block) super unless DELEGATE.include? name ::Kernel.send(name, *args, &block) end def respond_to_missing?(name, include_private = false) DELEGATE.include?(name) or super end end
Access to classes and modules from the Ruby standard library can be obtained in a BasicObject
subclass by referencing the desired constant from the root like ::File
or ::Enumerator
. Like method_missing
, const_missing can be used to delegate constant lookup to Object
:
class MyObjectSystem < BasicObject def self.const_missing(name) ::Object.const_get(name) end end
Raised when an IO
operation fails.
File.open("/etc/hosts") {|f| f << "example"} #=> IOError: not opened for writing File.open("/etc/hosts") {|f| f.close; f.read } #=> IOError: closed stream
Note that some IO
failures raise SystemCallError
s and these are not subclasses of IOError:
File.open("does/not/exist") #=> Errno::ENOENT: No such file or directory - does/not/exist
The GetoptLong
class allows you to parse command line options similarly to the GNU getopt_long() C library call. Note, however, that GetoptLong
is a pure Ruby implementation.
GetoptLong
allows for POSIX-style options like --file
as well as single letter options like -f
The empty option --
(two minus symbols) is used to end option processing. This can be particularly important if options have optional arguments.
Here is a simple example of usage:
require 'getoptlong' opts = GetoptLong.new( [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ], [ '--name', GetoptLong::OPTIONAL_ARGUMENT ] ) dir = nil name = nil repetitions = 1 opts.each do |opt, arg| case opt when '--help' puts <<-EOF hello [OPTION] ... DIR -h, --help: show help --repeat x, -n x: repeat x times --name [name]: greet user by name, if name not supplied default is John DIR: The directory in which to issue the greeting. EOF when '--repeat' repetitions = arg.to_i when '--name' if arg == '' name = 'John' else name = arg end end end if ARGV.length != 1 puts "Missing dir argument (try --help)" exit 0 end dir = ARGV.shift Dir.chdir(dir) for i in (1..repetitions) print "Hello" if name print ", #{name}" end puts end
Example command line:
hello -n 6 --name -- /tmp
The Vector
class represents a mathematical vector, which is useful in its own right, and also constitutes a row or column of a Matrix
.
Method
Catalogue To create a Vector:
Vector.elements
(array, copy = true)
Vector.basis
(size: n, index: k)
To access elements:
To set elements:
To enumerate the elements:
Properties of vectors:
Vector
arithmetic:
Vector
functions:
inner_product(v)
, dot(v)
cross_product(v)
, cross(v)
Conversion to other data types:
String
representations:
RDoc::Task
creates the following rake tasks to generate and clean up RDoc
output:
Main task for this RDoc
task.
Delete all the rdoc files. This target is automatically added to the main clobber target.
Rebuild the rdoc files from scratch, even if they are not out of date.
Simple Example:
require 'rdoc/task' RDoc::Task.new do |rdoc| rdoc.main = "README.rdoc" rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb") end
The rdoc
object passed to the block is an RDoc::Task
object. See the attributes list for the RDoc::Task
class for available customization options.
You may wish to give the task a different name, such as if you are generating two sets of documentation. For instance, if you want to have a development set of documentation including private methods:
require 'rdoc/task' RDoc::Task.new :rdoc_dev do |rdoc| rdoc.main = "README.doc" rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb") rdoc.options << "--all" end
The tasks would then be named :rdoc_dev, :clobber_rdoc_dev, and :rerdoc_dev.
If you wish to have completely different task names, then pass a Hash
as first argument. With the :rdoc
, :clobber_rdoc
and :rerdoc
options, you can customize the task names to your liking.
For example:
require 'rdoc/task' RDoc::Task.new(:rdoc => "rdoc", :clobber_rdoc => "rdoc:clean", :rerdoc => "rdoc:force")
This will create the tasks :rdoc
, :rdoc:clean
and :rdoc:force
.
A StringIO
duck-typed class that uses Tempfile
instead of String
as the backing store.
This is available when rubygems/test_utilities is required.
newton.rb
Solves the nonlinear algebraic equation system f = 0 by Newton’s method. This program is not dependent on BigDecimal
.
To call:
n = nlsolve(f,x) where n is the number of iterations required, x is the initial value vector f is an Object which is used to compute the values of the equations to be solved.
It must provide the following methods:
returns the values of all functions at x
returns 0.0
returns 1.0
returns 2.0
returns 10.0
returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
On exit, x is the solution vector.
Object
Notation (JSON
) JSON
is a lightweight data-interchange format. It is easy for us humans to read and write. Plus, equally simple for machines to generate or parse. JSON
is completely language agnostic, making it the ideal interchange format.
Built on two universally available structures:
1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array. 2. An ordered list of values. More commonly called an _array_, vector, sequence or list.
To read more about JSON
visit: json.org
JSON
To parse a JSON
string received by another application or generated within your existing application:
require 'json' my_hash = JSON.parse('{"hello": "goodbye"}') puts my_hash["hello"] => "goodbye"
Notice the extra quotes ''
around the hash notation. Ruby expects the argument to be a string and can’t convert objects like a hash or array.
Ruby converts your string into a hash
JSON
Creating a JSON
string for communication or serialization is just as simple.
require 'json' my_hash = {:hello => "goodbye"} puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
Or an alternative way:
require 'json' puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
JSON.generate
only allows objects or arrays to be converted to JSON
syntax. to_json
, however, accepts many Ruby classes even though it acts only as a method for serialization:
require 'json' 1.to_json => "1"
Kanji Converter for Ruby.