[go: up one dir, main page]

0% found this document useful (0 votes)
11 views34 pages

Rubysummary

This document provides a comprehensive overview of the Ruby programming language, detailing its features such as being interpreted, object-oriented, and having metaprogramming capabilities. It covers syntax, usage, built-in methods, exception handling, and class definitions, along with examples of conditionals, loops, and operators. The document serves as a guide for understanding Ruby's structure and functionality, making it a useful resource for both beginners and experienced programmers.

Uploaded by

Marcello Galli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views34 pages

Rubysummary

This document provides a comprehensive overview of the Ruby programming language, detailing its features such as being interpreted, object-oriented, and having metaprogramming capabilities. It covers syntax, usage, built-in methods, exception handling, and class definitions, along with examples of conditionals, loops, and operators. The document serves as a guide for understanding Ruby's structure and functionality, making it a useful resource for both beginners and experienced programmers.

Uploaded by

Marcello Galli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

A Temptative Summary of the Ruby Language

Marcello Galli, December-2014

Features
Interpreted, with reflection, metaprogramming.
Variables are references to objects
Garbage collection included
A lot built into the language (array,hashaes,characters, Dir etc. etc.)
Single things done in different ways, free syntax miming human language: optional returns,
block-delimiting statements and brackets in functions
Object Oriented; all is an object:

• single inherithance, but multiple module inclusion


• operator as methods, keywords as methods (=> "duck typing")
• one is always in the environment af an instance (defaults to "main")
• all the classes inherits "Object", including the "kernel*" module (with keywors as methods)
• the class definition is an instance of "Class" (whch inherits "Module*")
• all the methods have a "receiver" instance.
• there are instance methods and class methods (the receiver is the class as an instance of
"Class)
• There are: "public, private and protected methods"; default is: "public"
• strong encapsulation:

• class variables (prefix: "@@"),


• instance variables (prefix: "@"), available throught accessor methods
• local variables are really local
LEBG name resolutions( local, global, instance and class)

• global visible everywhere,


• instance and class prefixed by class or instance name
• Constants can't be defined into methods
• Constants defined outside classes are global
• scope operator "::, for module or class constants: "Math::PI"
symbols to acces the internal name table
All blocks have a return value (also Classes and method definitions)
Convention over declaration:

• capitalized constants (and class and module names)


• lowercase methods and variable names
• conventional prefixes: + "$" global variables + "@@" class variables + "@" instance variables
+ ":" symbol + "?" last character for function returning a boolean + "!" last character for function

A Temptative Summary of the Ruby Language Pg. 1


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
modifing things "in place" + "=" last character for function miming an assignment
Block arguments given to function, with extended usage of iterator blocks

Usage
• "irb" interactive shell with:

• "help" function
• "source" function to load files
• "conf" show the configuration
• "exit" command
• "ruby file.rb" , wioth parameters, as:

• ruby -e 'a=1 ; print "a=",a,"..OK\n " ;' ==> a=1...OK


• echo "aaaa" | ruby -n -e 'print $_.upcase' ==> AAA
• ruby file as an Unix shell command if first line: "#!/usr/bin/ruby"

Syntax
• case sensitive
• Blank lines ignored, multiple blanks are condensed;
• "#" comments, up to the end of the line.
• ";* , or a newline, to separate statements, but incomplete commands on multiple lines,
• backslash: "\" to escape a final newline
• "{ }" to define a block of statements;
• logical blocks begins with; begin class, def, if, do, end with "end".
• "__END__" on a line by itself, marks the end of the program
• special blocks:

• BEGIN { block executed at the beginning }


• END { block executed at the }
• multi-lines embedded document: =begin ... ..=end
• strings can be:

• double quotes: "stringan" ; %Q(abcdn) (backslash substitution performed)


• single quotes: 'stringa' ; %q(stringa) (only "\\" and "\`" substitution)
• array suntax: a=[1,2,3] ; a[0]
• hash syntax: b={"a"=>1,"b"=>2} ; b["a"]
• multiple assignements with array expansion:

a=b=c=3 # a,b,c , all reference to '3'


a,b=1,2 # a refers to one, b to two

A Temptative Summary of the Ruby Language Pg. 2


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
a,b=1,2,3,4 # extra elements are ignored
a,b,c=1,2 # c is unassigned (c==nil)

a,b=[1,2] # assignment be used to expand an array

x,*y=[1,2,3] # extra elements are assigned to an array: x => 1 ; y => [2, 3]

*y,x=[2,3,1] # since Ruby 1.9 the array can be in the first position
a,*y,b=1,2,3,4,5 # and can also be in the middle: a => 1 ; y => [2, 3, 4] ; b => 5

x,y,z=1,*[2,3] # assignment used to expand an array: x=>1 ; y => 2 ; z => 3

• constants can be changed


• inclusion of external files: + load 'nomefile.rb' # also for compiled libraries + require 'nomefile' # the
".rb" suffix assumed, loads only once, from $LOAD_PATH + require_relative 'nomefile' # path
relative to current directory
To add a path: $LOAD_PATH.unshift('./')

Predefined variables and constants


Constant Meaning
$0 name of the Ruby program ( also: $PROGRAM_NAME)
$* array with command line options (also: ARGV)
$" array of included modules
$: path for module searching
$stderr, $stdout, $stdin standard I/O streams
$_ last read line
$; default string separator for the split function
$, separator for printed items (default is nil)
$! last raised exception
$@ backtrace for last raised exception
$& for regular expression: matched string
$` substring before the match
$' substring after the match
$1...$n sub-expressions in the match
$? status of the last sub-process (contains the Status object)
ARGV command line options (array of strings) ARGV[0] as first option
ENV hash of environment variables
RUBY_DESCRIPTION description of the Ruby version
RUBY_PLATFORM the computer type
RUBY_VERSION Ruby version number

A Temptative Summary of the Ruby Language Pg. 3


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
Statements
Conditionals
• The if , then, else statement:

if a==0 then b=77 end # if on a single line, "then" is mandatory

if boolean-expression then
statements
elsif boolean-expression then
statements
else
statements
end

• unless, same as: "if not .."

unless a==0 then b=77 end

unless boolean-expression then


statements
else
statements
end

• The case statement:

case target-expr
when comparison , comparison ... then
statements
when comparison , comparison ... then
statements
else # optional else
statements
end

name = case x
when 1 # new line as a separator
"one"
when 2 then "two" # then used as a separator
when 3; "three" # semicolon as a separator
else "many"
end

case 74.95
when 1...50 then puts "low"
when 50...75 then puts "medium"
when 75...100 then puts "high"
end

Loops

A Temptative Summary of the Ruby Language Pg. 4


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
• The infinite loop:

loop do
statements
end

loop { a+=1 ; print(a) ; break if a>3 } # loop on a single line

• The while loop:

while boolean-expression do
statements
end

x = 0
while x < 10 do puts x = x + 1 end # loop on a single line

• The until loop (same as: while not):

until boolean-expression do
statements
end

• while and until loops executed at least once, (condition at the end):

x = 10
begin # Starts the conditional block, executed at least once
puts x
x = x - 1
end until x == 0 # condition evaluated at the end

a=10
begin
a+=1
end while a<3

• The for loop:

for name, name in sequence do


statements
end

a=[1,2,3,4]
for i in a
print i
end

for i in a ; print i ;end


for i in a do print i ;end

for i in (1..3) do print i ; end # range usage in the loop

hash = {:a=>1, :b=>2, :c=>3}

A Temptative Summary of the Ruby Language Pg. 5


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
for key,value in hash
puts "#{key} => #{value}"
end

• Statements altering the loop flow:

• break : terminates loop immediately; can have an optional argument that is is the loop
result
• next : goes to the next iteration.
• redo : repeats the iteration, without testing again the condition.
• retry : repeats the iteration, testing again the condition.

for i in a
break if i==3
next if i==2
print i
redo if i==1 # this is an infinite loop
end

• catch, throw :
The catch statement defines a block, which is interrupted by a throw statement. The catch block has a
label, and the throw send to the end of the block with the label:

for matrix in data do # A deeply nested data structure.

catch :label do # begin of the catch block


# the block has the label: ":label"
for row in matrix do
for value in row do
throw :label unless value # Break out of two loops at once,
statements # otherwise, executes these statements.
end
end

end # end of the catch block

end

Exception Handling
General form:

begin
...
raise exception_name

rescue Exception_class,Exception_class => local_name_for_exception

.... (block executed if given the exceptions have been raised )

rescue Exception_class,Exception_class => local_name_for_exception

A Temptative Summary of the Ruby Language Pg. 6


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
.... (block executed if given the exceptions have been raised )

else

... block executed if no exception in main block

ensure

.... block executed in any case


end

Raise examples:

raise "message error" if n < 1

raise RuntimeError.new("message error") if n < 1

raise RuntimeError.exception("message error") if n < 1

Examples

begin

raise "negative value" if x<0 # raise the exceptions


y=Math::sqrt(x)

rescue => ex # Stores the exception in the local variable ex

puts "#{ex.class}: #{ex.message}" # Handle exception

end

begin
y=Math::sqrt(x)
rescue DomainError => ex
puts "Try again with a value >= 1"
rescue TypeError,ArgumentError => ex
puts "Try again with an integer"
end

y = Math::sqrt(x) rescue 0 # to give an alternative value

Postfix Expressions
expr if bool-expr # the same as: "if expr then ... end" )
expr unless bool-expr # the same as "unless bool-expr then ... end")

Examples:

exit if not str or not str[0]

a=1 if a.nil?

A Temptative Summary of the Ruby Language Pg. 7


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
x = 0
puts x = x + 1 while x < 10 # The while condition is at the end

a = [1,2,3]
puts a.pop until a.empty? # The until condition is at the end

Operators
Operator Meaning
= assignment : a=1
+= -= *= operation and re-assignment, implemented for all numerical operators
:? ternary operator
&& logical and
|| logical or
not logical negation
or logical operator "or" with lower precedence
and logical operator "and"with lower precedence
.. ... range operators (create range objects)
defined? nil if not defined, otherwise the type: Es.: a=1; defined?(a) => "local-variable"

The operators of the form: "+=,-=,*=" etc. are shorthands for operation and assignment.
The "++" operator doesn't exists in Ruby.
Examples:

var || =77 # an undefined variable is false; the assignment is executed.

1==1 ? 'Yes' : 'No' # the condition is true, the operator returns: 'yes'
1==2 ? 'yes' : 'No' # the condition is false, the operator returns: 'No'

A Temptative Summary of the Ruby Language Pg. 8


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
Classes and methods
Definitions
class Classname < Superclasse # class definition (inherits Superclasse)

include Modulename,Othername # the class includes these modules


include(OtherModulename)

attr_accessor :x,:y # creation of accessor methods


attr_reader :u,:w
attr_reader "v","z"

@@n=0 # a class variable

def initialize(x,y=3) # class constructor

@x,@y=x,y # instance variables


# must initialized in the constructor

super( a, b, c ) # calls the constructor of the parent


end

def self.classmethodname # definition of a class method (uses self)


...
end
class << self # block containing class methods
def nome(..)
...
end
end

def metodo # definition of an instance method (no self)


.....
end

to_s # override of a function of a parent class


"description class"
end

protected # section for protected methods

here protected methods

private # section for private methods

here private methods

end

Methods to look at the structure of a class hierarchy:

Classname.superclass # show the inherited class


Classname.ancestors # show all the inherited classes (ancestors)

A Temptative Summary of the Ruby Language Pg. 9


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
Classname.methods # show all the methods
Classname.constants # show the constants defined in the class

Classname.included_modules # list of the included modules


Classname.include?(Nomemodulo) # tests if a module is included

Classname.respond_to?("string") # tests if a method exists


Classname.respond_to?(:symbol) # tests if a method exists, using a symbol

Instances:

instancename=Classname.new(argument, arg, arg2)

instancename.instance_of? Classname # to test if instance of a class


instancename.kind_of? Classname # to test if a class is among ancestors

Calling functions:

Classname.classmethodname(..) # for class methods


instance.methodname(..) # for instance methods

Methods can be defined outside the class definition:

def Classname.classmethodname(..)
....
end

Singleton methods, belonging to a single instance:

oggetto=Classname.new
def oggetto.funzione(..) # singleton method,
...
end

a="1"
def a.nome
print "uno"
end

a.nome => uno

Method calls
• Arguments with default values:

def iniziostringa(s, caratteri=1)


s[0,caratteri] # a substring of a given length
end

iniziostringa("Abcdef") => "A"


iniziostringa("Abcdef",3) => "Abc"

A Temptative Summary of the Ruby Language Pg. 10


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
def iniziostringa(s, caratteri=s.size-2)
s[0,caratteri]
end

• Variable number of arguments: some arguments going into an array:

def stampa(a,*b)
print(a," ",b)
end

stampa("a") => a []
stampa("a","b") => a ["b"]
stampa("a","b","c") => a ["b", "c"]

• Array arguments expanded to multiple values ("splat" operator):

def stampa(a,b,c)
print("a=#{a} ","b=#{b} ","c=#{c} ")
end

stampa(*[1,2,3]) => a=1 b=2 c=3 # there are 3 values into the function

A Temptative Summary of the Ruby Language Pg. 11


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
Block arguments
funcname(a,b,c,d) { |x,y,z| statements and function of x,y,z .. }

def funcname(a,b=3,*e)
....
....
if block_given?
yield x1,y2,z1 # here the block is executed, with arguments x1,y1,z1
end
...
...
end

def iterfun(k)
a=[1,2,3,4]
for ia in a
yield ia*k if block_given?
end
end
iterfun(1) # returns => [1, 2, 3, 4] the last evaluated object
iterfun(1){ |k| print k } => prints 1234
iterfun(2){ |k| print k } => prints 2468

def yfunc(a)
b=0
a=a+1
yield a,b #argument are passed to the block only once
end
yfunc(1){|k,j| print(k,j)} # => 20

def a_method
return yield if block_given? # testing if the block exists
'block missing'
end
a_method # => "block missing"
a_method { "block found!" } # => "block found!"

# value of the block, returned by "yield" into the function,


# used by function computations.

def a_method(a, b)
a + yield(a, b)
end
a_method(1, 2) {|x, y| (x + y) * 3 } # => 10

proc and lambda


Blocks of statements executable with the "call" method:

A Temptative Summary of the Ruby Language Pg. 12


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
myproc = Proc.new {|wine| puts "I love #{wine}!"}
myproc.call("sangiovese") #=> I love sangiovese!

func(a,b,c,d,&procname) # proc in the call


def func(arg,arg2,arg3=default, &block) # as function argument
..
the name: block contains the proc
..
end

def stampa(&block)
block.call # here the block is called as it where a *proc*
yield # here the block is called by yield
end

myproc = lambda {|x| puts "Argument: #{x}"} # Lambda are equivalent to Proc

myproc.call("ABCDE!") # => Argument: ABCDE!

Object Class and methods


Method Function Examples
nil? test if nil (only a nil value returns true) Es,: nil.nil? => true
is_a? ; kind_of? tests if class or ancestor 1.is_a? Numeric => true
instance_of? tests if instance of a class 1.instance_of? Fixnum => true
respond_to? test if a class method 1.respond_to?('+') => true
methods array with public methods Object.methods => [:allocate, :new,....]
method returns a Method object 1.method("+") => #<Method: Fixnum#+>
send calls a method on an instance 1.send("+",2) => 3
clone clones an object s2=s1.clone
dup makes a shallow copy of an object (copies only the references, not the data)
abort stops the program abort("messaggio")
exit exits from the program, raising SystemExit. Es.: exit(1)
exit! exits, skipping then exception handling mechanism
fork creates a sub-process
exec executes a process, in place of the current one. exec("ls")
spawn executes a command in a subshell. spawn("ls")
sleep(s) pause the program for some seconds sleep(5)
system executes a system command. system("ls")
command command for the system ls => lists current directory
%x{command} command for the system as ``, but using a different separator

A Temptative Summary of the Ruby Language Pg. 13


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
warn writes a message on stderr. warn("attention")
eval evaluates a ruby expression. a=1;b=2; eval("a+b") =>3
load loads and execute a ruby program. load("nomefile.rb)
freeze makes an object immutable
frozen? tests if an object is immutable

Integer creates an integer object


Float creates a float object
Complex creates a Complex object
Rational creates a Rational object
Array creates a Array object
String creates a String object
=== tests if an object is a parent

Logicals
• true, false, nil are single instances of TrueClass, FalseClass and NilClass
• Logical classes implement the logical operators: "& | ^".
• empty objects are "true"
• defined?" returns nil if an object is not defined, classes and function definition return "nil";
• conversions from "nil":

nil.to_a => [] : empty array


nil.to_c => (0+0i) : complex zero
nil_to_s => "" : empty string
nil.to_f => 0.0 : zero
nil.to_i => 0
nil.to_r => (0/1) : rational zero

Numeric Classes
0x is the prefix for hexadecimal representations
0b is the prefix prefix for binary representation
0 is the prefix prefix for octal representation
Floats are double precision , always a digit is needed before and after the point: ".1" or "1." are not
valid float numbers.
Underscores can be used inside numbers to separate digits: a=1_000_000 => 1000000
The subscript operator "[]" can be used for Fixnum, and returns single bits of a number
Special values for floats:

0.0/0.0 => NaN


1.0/0.0 => Infinity

A Temptative Summary of the Ruby Language Pg. 14


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
0/0 => ZeroDivisionError: ....

Rationals and Complex:

Complex(1) => (1+0i)


Complex(2, 3) => (2+3i)
Complex(0.3) => (0.3+0i)
Complex('0.3-0.5i') => (0.3-0.5i)

Complex(2, 3).real => 2 # real part


Complex(2, 3).imag => 3 # imaginary part)
Complex(2, 3).conj => (2-3i)

Complex(0,1).phase => 1.5707963267948966 # radians


Complex(0,1).polar => [1, 1.5707963267948966] # modulus, phase
Complex(0,1).rect => [0, 1] # Array with real and imaginary parts

a=Rational("1/2")
a=1.quo(5) # division between integers that gives a rational number

Rational(1) => (1/1)


Rational(2, 3) => (2/3)
Rational(4, -6) => (-2/3)
Rational('0.3') => (3/10)
Rational('2/3') => (2/3)
Rational('0.5') => (1/2)

(Rational(3,2)).numerator => 3
(Rational(3,2)).denominator => 2
(Rational(3,2)).truncate => 1
(Rational(3,2)).round => 2

Methods for numerics


Operator Function Examples
** ; pow(x,y) power a**3
*/ Multiplication,division a*b ; 3*2 => 6 ; 3/2=1
% Remainder 5/2. => 1.0
+- Addition, subtraction a+b ; 2+5 => 7
<< >> bitwise shift 4<<1 => 8
&|^ bitwise and, or, xor
<=> comparisons, returns: -1, 0 , 1 ; if less, equal greater
< > <= >= comparisons 4<1=> false
between? inclusion in a range 2.between?(1,4) => true
== != equal, not equal
zero? true if zero 3.2.zero? => false
eql? same value AND type 1.0.eql? 1 => false
equal? reference equality: if a is the same object as b: a.equal?(b) => true

A Temptative Summary of the Ruby Language Pg. 15


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
abs ; magnitude Absolute value -1.abs => 1
abs2 square modulus -2.abs2 => 4
ceil minimum greater integer 1.2.ceil => 2 ; -1.2.ceil => -1
floor maximum lower integer 1.7.floor =>1 ; -1.2.floor =>-2
round rounds a number 1.4.round => 1 ; 1.5.round => 2
div integer division 5.2.div(2.0) => 2
divmod quotient and remainder 5.divmod(2) => Array :[2, 1]
fdiv float division 3.fdiv(2) => 1.5
quo division with maximum precision (Rational numbers if integer operands)

Methods for Integers


even? true if even 2.even? => true
odd? true if odd 3.odd? => true
next ; succ next integer 1.next => 2
pred previous integer 2.pred =>1
gcd greatest common denominator 10.gcd(15) => 5
lcm lowest common multiple 10.lcm 15 => 30

Methods for Floats


finite? true if finite (1.0/0.0).finite? => false
infinite? test if infinite (-1.0/0.0).infinite? => -1
nan? test if not a number (0.0/0.0).nan? => true

Conversion Methods
**to_s** # converts to string, for fixmum the argument is the base, es.:

16.to_s => "16" ;


16.to_s(2) => "10000" ;
16.to_s(16) => "10"

**to_i** # converts to integer;

**to_f** # converts to float;

**to_r** # converts to rational

Precedence for operators (high to low precedence):

[ ] [ ]=
**

A Temptative Summary of the Ruby Language Pg. 16


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
! ~ + - (unary operators)
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
?:
= %= /= -= += |= &= >>=
<<= *= &&= ||= **= ^=
not
or and
if unless while until
begin/end

String Class
Creation:

a=String.new("characters")

a="stringa\n" # with backslash substitutions


a=%Q(abcd\n) # () are used as delimiters
a=%QZ 12 ef(), Z # 'Z' is used as a delimiter

a='stringa' # without backslash substitutions


a=%q(stringa) # () are used as delimiters
a=%qA xyx string aad A # The letter 'A' is used as a delimiter

Commparisons:

'0'<'A' => true


'A'<'a' => true
'a'<'b' => true

'azzz'<'baaa' => true # the first different characters matters!


'aab'<'abb' => true
'abc'<'abc0' => true # the second string is longer

Encoding (each string has its own encoding):

'a'.encoding => #<Encoding:UTF-8>

b='a'.encode("ISO-8859-1")

b.encoding => #<Encoding:ISO-8859-1>

b.encode!("UTF-8") # encode! changes the string on-place

A Temptative Summary of the Ruby Language Pg. 17


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
b.encoding => #<Encoding:UTF-8>

"abcd".encode("UTF-8", undef: :replace, replace: "X") # "X" replaces undefined characters


"abcd".encode("UTF-8", invalid: :replace, replace: "X") # "X" replaces invalid characters

b='a'.encode("ISO-8859-1")
b.force_encoding("UTF-8") # tells to Ruby that b is an UTF-8 string,
b.encoding => #<Encoding:UTF-8> # but 'b' is not changed

+ concatenates strings: "a"+"b" => "ab"


* repeats strings: "abc" * 2 => "abcabc"
<< concatenates strings: "a"<<"b" => "ab"
ascii_only? true if only ascii characters
empty? true if empty
end_with?("string") true if end with the given string
include?("substring") test if substring included: 'abc'.include?(b)=> true
index("substring") index of a given substring: 'abc'.index('b') => 1
rindex("substring") index of a given substring starting from the end
insert(index,string) substring insertion: "abc".insert(1,"xx")=>"axxbc"
split(pattern) splits into an array, default pattern is a space
capitalize ; capitalize! makes the first character uppercase
uppercase ; uppercase! to upper cases; uppercase! changes string in place
downcase ; downcase! to lowercase
swpacase ;swapcase! upper case to lower and lower to uppercase
sub(pattern,replacement) first occurrence substring replacement
gsub(pattern,replacement) all occurrence substring replacement
tr('old char','new') .tr! change characters, as the "tr" Unix command
center(n," ") centers in n characters, specifying the padding character
ljust(n," ") shifted to left, in n characters, padded with space
rjust(n," ") shifted to right
lstrip ; lstrip! strip leading spaces
rstrip ; rstrip! strip final spaces
strip ; strip! strip final and leading spaces
squeeze(characters) ;squeeze eliminates duplicates for the given characters
reverse ; reverse! reverse the string
clear empties the string
replace(newstring) replaces the string with a new one
chomp ; chomp! strips the final end of line, if present
encoding returns the string encoding

A Temptative Summary of the Ruby Language Pg. 18


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
valid_encoding? if a valid encoding
encode("iso-8859-1") ; encode! re-encode the string in the given encoding
force_encoding("utf-8") tell the encoding to Ruby
to_i ; to_f conversion to numbers
length ; bytesize length in characters or bytes
getbyte(num) get a single byte at a given position
setbyte(num) set a single byte at a given position
bytes.to_a byte contents: "ab".bytes.to_a =>[97, 98]
count("substring") counts how many times the substring is found
count("a-c") count characters
delete("chars") delete!("b") delete characters
crypt crypt the string using the operating system function
sum computes a simple checksum for the string
next ; succ next in the ascii sequence: "a".next => "b"
ord encoding number of first character : "ab".ord => 97

• The function "chars"


It is used to separate a string into an array of characters (produces an Enumerator object):
"string".chars.to_a => ["s", "t", "r", "i", "n", "g", "a"]
• count and delete
can count or delete ranges of characters, characters out of a range etc.:
"abccd".count("a-c") => 4 ; "abccd".count("^a-c") => 1 ; "abcdeff".delete("a-cf") => "de"
• sub and gsub
can have a regular expression or a string as the pattern argument, also the subsequences of the
match can be used:

"abcdcde".sub("cd","xy") => "abxycde"

"abcdcde".gsub("cd","xy") => "abxyxye"

• slice
can be used to extract substrings, as the [] operator;
"abcde".slice(2..4) => "cde" "abcde".slice(1,3) => "bcd" "abcde".slice("bcd") => "bcd"
• The "?" operator
gives the representation of a single character in a string:
?a => a ; ?C-d => "u0004" # this is the unicode for Cntrl/d
• The [] operator
extract characters from strings,
• String interpolation:
A Ruby expression can be inserted into a string, and its result is computed and used into the
string:

A Temptative Summary of the Ruby Language Pg. 19


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
"stringa #{ruby statements } ... "
• The format operator "%" :
this operator acts the same as in the printf routine of the C language:
" string with %s %d " % ['abc',123] => " string with abc 123 "
• The plus operator "+"
this operator is used to concatenate strings.
"abc"+"def" => "abcdef"
Strings following strings are automatically concatenated:
a='asd' 'asd' => "asdasd"
• The operator "*"
this operator is used to repeat strings.
"a"*3 => "aaa"
• Here documents:
very long string can be inserted in the following way (HERE is an arbitrary word, used as a
delimiter):

nomestringa = <<HERE
here a long text

HERE

Array Class
Array creation:

a=Array.new : an empty array


a=Array.new(3) : to make an array of 3 elements containing "nil"
a=Array.new(3,"a") : to make an array of 3 elements containing the object: "a"

a=[12,"asd",3.5E3,1,2,3] : another way to make an array

To make an array from words in a string:

a= %w{ a b \n } => ["a", "b", "\\n"] # no backslash substitution


a= %W{ a b \\n } => ["a", "b", "\n"]

split and join

"1-2-3".split("-") => ["1", "2", "3"]


[1,2,3].join("-") => "1-2-3"

[1,2]*"a" => "1a2"

to_a, a member of Enumerable, creates an array from a sequence.


zip combines arrays element by element, producing an array of arrays:

A Temptative Summary of the Ruby Language Pg. 20


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
(1..3).zip [ "a","b","c"] => [[1, "a"], [2, "b"], [3, "c"]]
[1,2,3].zip([10,20,30],["a","b","c"]) => [[1, 10, "a"], [2, 20, "b"], [3, 30, "c"]]
(1..3).zip => [[1], [2], [3]]

+ concatenates: "a"+"b" => "ab"


- difference: [1,1,2,3] - [1,2,4] => [3]
* array repetition: [1]*2 => [1, 1]
concat concatenates: [1].concat([2]) => [1, 1]
& common elements: [1,2] & [2,3] => [2]
| add without duplicates: [2,2,3] | [1,2,4] => [ 2, 3, 1, 4]
<< append elements: [1]<<2 => [1, 2]
include?(value) true if the value is included: [1,2].include?(1) => true
empty? true if empty
length number of elements
count counts elements: [1,2,1].count => 3 ; [1,2,1].count(1) => 2
compact ; compact! removes nil elements
uniq ; uniq! remove duplicates: [1,2,2].uniq => [1, 2]
delete(value) fetches and deletes an item, given its value
delete_at(n) fetches and deletes an item, given the position
insert(index,value) insert at the given position: [1,2].insert(1,5) => [1,5,2]
fill(value) change each element to the given value
first(n) first elements: [1,2,3].first(2) => [1, 2]
last(n) last elements: [1,2,3].last(2) => [2, 3]
max maximum element: [1,3,2].max => 3
min minimum element: [1,3,2].min => 1
flatten makes uni-dimensional: [[1,2],[3,4]].flatten => [1,2,3,4]
transpose in 2-dimensional transposes row and columns
join(separator) joins elements into a string: [1,2].join("-") => "1-2"
combination(n).to_a array with the all combinations of n elements of the array
permutations(n).to_a all permutations of n elements
repeated_combination(n) all combinations with repetitions
repeated_permutations all permutations with repetitions
replace(newarray) replaces with an other array
reverse ; reverse! reverses the order o f elements
rotate(n) ; rotate!(n) circular shift: [1,2,3].rotate(1) => [2, 3, 1]
sample(n) extracts n random elements
unshift(1) add a first element [1].unshift(2) => [2, 1]

A Temptative Summary of the Ruby Language Pg. 21


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
shift(n) extracts and deletes first n elements
push(value) add an element at the end: [1].push(2) => [1, 2]
pop(n) extract and deletes elements from the end
shuffle ; shuffle! random reordering
sort ; sort! sorts elements:[2,1].sort=>[1, 2]; ["b","a"].sort=>["a","b"]
to_s a string representing the array

flatten has an optional argument: the number of dimension to eliminate:

a=[1,2,[13,14],[15,[26,[37,38]]]]

a.flatten(1) => [1, 2, 13, 14, 15, [26, [37, 38]]]


a.flatten(2) => [1, 2, 13, 14, 15, 26, [37, 38]]
a.flatten(3) => [1, 2, 13, 14, 15, 26, 37, 38]
a.flatten => [1, 2, 13, 14, 15, 26, 37, 38]

The Subscript Operator: []


"[]" returns single bits for numbers, characters for strings, elements of arrays; inside the square brackets:
numbers, ranges or also regular expressions:

a=[1,2,3,4] ;

a[0] => 1 # index begins from zero


a[-1]=> 4 # negative indexes from the end
a[a.size-1] # last element

a[0..2] => [1, 2, 3] # extracts using a range (last element included)


a[0...2] => [1, 2] # extracts using a range (last element NOT included)
a[-4..-2] => [1, 2]

a[0,2] => [1, 2] # a sub-array (2 elements from 0)


a[1,2] => [2, 3] # 2 elements , from 1
a[-3,2] => [2, 3] # 2 elements , from -3 ( a[-3]=> 2 )
a[-4,2] => [1, 2] # from element -4 (the first) takes 2 elements

a[/regular expr/] # regular expressions can be used too

a.first(2) => [1, 2] # first elements


a.last(2) => [3, 4] # last elements

a=[1,2,3,4] ; a=['a','b']=> ["a", "b", 2, 3, 4] # reassigns a range of elements

An element is changed or added with the "[]=" operator; nil elements are created to void the gaps:

a=[0] ; a[3]=3 => [0, nil, nil, 3]

a=[1,2,3,4]
a[0,2]=0 => [0, 3, 4] # starting from position 0, sets 2 elements

a=[1,2,3,4]

A Temptative Summary of the Ruby Language Pg. 22


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
a[0,2]=5,6 => [5, 6, 3, 4] # multiple assignments are possible
a[0,2]=[5,6] => [5, 6, 3, 4]

a=[1,2,3,4]
a[-1]=9 => [1, 2, 3, 9] # negative indexes counts from the end

Hash Class
Symbols can also be used as keys, for a faster access::

a={"one" => 1, "two" =>2 ,3 => "a"}

a["one"] => 1
a[3] => "a"

h["a"]=723 # adds, or replaces, en element


h={ :one => 1, :two =>2 } # symbols can be used as keys

h={one: 1 , two: 2 } # alternate syntax, possible when keys are symbols

a=Hash.new makes an empty hash


a={} makes an empty hash
a=Hash.new("default") makes an empty hash defining the default value
default returns the default value
default= sets the default value
delete deletes an element by key Es.: h.delete("one")
fetch fetches element by key: h.fetch(key)
has_key? ;include? : key? True if a key is present: h.has_key?(k)
has_value? true if a value is present: h.has_value?(val)
merge ; merge! merges hashes, duplicate keys are overwritten: h.merge(h2)
sort sorted array of pairs: [[key1,value],[key2,value]..]
flatten(n) array with keys and values, with n dimensions flattened
invert keys become values and values keys
flatten(n) array with keys and values, with n dimensions flattened
empty? true if the hash is empty: {}.empty? => true
length ; size number of elements
values array with values
h.keys array with keys
h[key] a value, given the key (the default value if key not found)
h[key]=value adds, or changes, the value for a given key
key(value) a key, given a value
clear voids an hash

A Temptative Summary of the Ruby Language Pg. 23


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
sort an ordered array of [key,value] ,ordered by keys
shift extracts and remove the first [key,value] pair
to_a array of [key,value] pairs
to_s a string representing the hash

Range Class (intervals in sequences)


Creation:

a=Range.new(1,3)
1..3 => 1,2,3 # last element is INCLUDED

a=Range.new(1,3,true)
1...3 => 1,2 ; range with last element NOT INCLUDED

(1...3).exclude_end? : true

-3..-1 => -3,-2,-1

'a'..'c' # range of characters

1.2..3.5 # range of float (but you can't iterate on these)

a=[0,1,2,3,4]
a[1..3] => [1, 2, 3]
a[1...3] => [1, 2]

Array of ranges (ranges are not automatically expanded):


a=[1..3,5...9] => [1..3, 5...9]

exclude_end? tests if last value is included: (1...3).exclude_end? => true


cover? tests if between bounds: (1...3).cover?(2.5) => true
include? ; member? tests if member of the range: (1...3).include?(3) => false
begin the range begin: (1..3).begin => 1
end the range end: (1...3).end => 3
first(n) first n elements: (1..3).first(2) => [1, 2]
last(n) last n elements (1..3).last(2) => [2, 3]
min minimum value (1...3).min => 1
max maximum value: (1...3).max => 2
to_a converts to array: (1..3).to_a => [1, 2, 3]
to_s string representation (1..3).to_s => "1..3"

Regexp class: (regular expressions objects


Creation:

A Temptative Summary of the Ruby Language Pg. 24


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
r=/pattern /

r=/pattern /options

r=%r{pattern} # every character can be used in place of "{}"

r=%r{pattern}options # a regular expression with options

r=Regexp.new(pattern,options)

Options:

i : case insensitive search


o : a substitution is performed only once
m : the dot match also \n
x : extended syntax

the match method returns instead a MatchData object


match operator: "~=" (returns the index of the first match or nil)

string =~ /pattern/ # returns a number or nil:


n= string =~ /pattern/

/pattern/.match(string) # returns a MatchData object:


matchdata = /pattern/.match(string)

string !~ /pattern/ # is the same as !(string =~ /pattern/)

the match method returns instead a MatchData object


Matchdata object (saved in the global variable: "$~):

$& matchdata[0] the matched part of the string


$' matchdata.pre_match the part preceding the match
$` matchdata.post_match the part after the match
$1 $2 matchdata[1] strings matched by sub-patterns
matchdata,size size of the matched string

sub makes a single substitutions, gsub changes all the occurrences:

"string".sub(/pattern/,"replacement string")

"string".gsub(/pattern/,"replacement string") # gsub for multiple substitutions

"string".sub!(/pattern/) # sub!: for on-place replacement


"string".gsub!(/pattern/)

scan : subdivides strings using regular expressions:

"one word or two".scan(/\w+/) => ["one", "word", "or", "two"]

A Temptative Summary of the Ruby Language Pg. 25


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
"one word or two".scan(/\w+/) {|w| statements } # also passing matches to a block
"string".scan(/(t).*(n)/) { |a,b| print a,b } # sub-matches given to the block

Patterns
. the dot matches any character
+ one ore more of the preceding substring
* zero or more of the preceding substring
? one or zero of the preceding substring
[abc123] one of these characters
[^aeiou] a character not in the list; not a vowel for: [^aeiou]
[a-c] a range of characters
[^a-c] a character not in the range
a|b logical or for characters ( "a" or "b" )
{m} m times the preceding substring
{n,m} min m and max m occurrence of the preceding substring
{,m} at least m times
{,n} at most n
^ the beginning of a line
$ the ending of a line
\Z ending of a string
\A beginning of a string
\b word boundaries
\B non word boundaries
\s space characters (and also \n \t \r \f )
\S NON space characters
\d a digit, same as [0-9]
\w a word character, same as [A-Z,a-z,0-9_]
\W a non word character
() to group characters into a sub-pattern
\1 \2 substrings matched by a preceding sub-pattern

Examples:

match position matched string meaning


/abc/ =~ "012abc34" 3 "abc" "abc" substring
/^abc/ =~ "012abc34" nil nil not "a", then "bc"
/d+/ =~ "012abc34" 0 "012" some digits

A Temptative Summary of the Ruby Language Pg. 26


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
/.+s.+/ =~ "123 abc" 0 "123 abc" first space between characters
/4$/ =~ "4234" 3 "4" "4" at the end
/(34)$/ =~ "34234" 3 "34" "34" at the end
/^(34)/ =~ "34234" 0 "34" "34 at the beginning
/3{2}/ =~ "12343312" 4 "33" "3" two times
/[0-9]/ =~ "abc3de" 3 "3" a character in a range
/(dd):(dd)/=~"a12:30" 1 "12:30" subpattern: $1=>"12"; $2=>"30"

Other Builtin Classes


• Dir
to manage directory and files, methods: chdir, pwd, exists?, mkdir, new, delete.
• Exception
to manage exceptions with methods: message , status, success? (true is status zero or nil) to_s
: a string representation of the message
• File
represents files, with all the usual unix functions: atime, ctime, dirname, executable?, directory?,
file? ,exists?, readable? ,zero?, truncate, delete, new, rename, ftype, lstat ,link, symlink, path,
size, stat
• IO
for input/output and functions as: new, pipe, open, read, write, sync, eof?, and many iterators on
the file content.
• Random
random numbers
• Struct
A mini-class to contain strings which can be accessed by symbols:

Customer = Struct.new(:name, :surname) # => makes the Customer object

c1=Customer.new("giovanni", "bianco") # makes instances


c2=Customer.new("giovanna","rossi")

c1.name => "giovanni" # using builtin accessors


c1["name"] => "giovanni"

c1.members=> [:name, :surname] # using symbols as accessors

c1.to_a => ["giovanni", "bianco"]

c1.to_h : make an hash ( only for Ruby 2 )

• Time
class for time and date:

A Temptative Summary of the Ruby Language Pg. 27


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
t = Time.at(0) => 1970-01-01 01:00:00 +0100
t1= Time.gm(2000,"jan",1,20,15,1) => 2000-01-01 20:15:01 UTC
t2= Time.local(2000,"jan",1,20,15,1) => 2000-01-01 20:15:01 -0600
t3= Time.new(2010, 12, 25, 8, 0, 0, "-06:00") # => 2010-12-25 08:00:00 -0600
tn=Time.now => 2014-08-27 16:04:34 +0200
tn.getgm => 2014-08-27 14:06:40 UTC # convert from local to UTC
Time.now.asctime => "Wed Aug 27 16:05:51 2014" # as an ASCII string

tn.strftime(special string ) # formatted as in the printf function of C


tn.strftime("today is %d/%m/%Y %H:%S") => "today is 27/08/2014 16:40"

tn.to_a => [40, 6, 16, 27, 8, 2014, 3, 239, true, "CEST"] # as an array
to_f ; to_i => giulian seconds from 1870
localtime ; gmtime ; => convert times in place

Parts of the data can be obtained by:

t = Time.at(0)

t.min ; t.sec ; t.hour;


t.hour ; t.day ; t.mon; t.year; t.zone ;
t.wday ; t.mday;
t.sec ; t.usec ; t. nsec => in julian seconds, microseconds, nanoseconds

Iterators
The Enumerator Class:

a=Enumerator.new([1,2,3])

a.each {|k| print k} => 123

a.next => 1
a.next => 2 # extract, and consume the element
a.peek => 3 # only fetch the current element
a.peek => 3 # always the same element without a "*next*"
a.next => 3
a.next => raise a StopIteration exception

a.rewind # to begin again the sequence


a.next => 1

Enumerable Module Methods:

all? true if all the elements are true. Es.: [0,true,nil].all? => false
any? true if some elements is true. Es.: [0,true,nil].any? => true
collect ; map array obtained by the block: (1..2).collect {|a| a*2} => [2, 4]
count counts true values from block: (1..6).count {|a| a<3 } => 2
cycle(n) cycles n time over the sequence: [1,2].cycle(2) {|a| print a} => 1212
detect return the first true element: (1..6).detect {|a| a>3 } => 4
drop(n) array without the first n elements: [1,2,3,4].drop(2) => [3, 4]

A Temptative Summary of the Ruby Language Pg. 28


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
drop_wile drops until block returns true: [1,2,3,4].drop_while {|a| a < 3 } => [3,
4]
take_while take until block returns false: [1,2,3,4].take_while {|a| a < 3 } => [1,
2]
each_slice(n) loops on groups of n values:(1..4).each_slice(2){|a| print
a}=>[1,2][3,4]
each_with_index value and index to the loop:(1..3).each_with_index{|a,i| print
a,i}=>102132
find_all ; select all elements for which the block is true: (1..3).find_all {|a| a>1}=>[2, 3]
reject all elements for which the block is false: (1..3).reject {|a| a>1} => [1]
find_index index of first element giving a true block: (1..3).find_index{|a| a>1} => 1
first(n);take(n) first n elements: (1..4).first(2) => [1, 2]
grep(pattern) array of matching elements:["a","b","c"].grep(/b|c/){|i|
i}=>["b","c"]
include? true if an element is included: (1..3).include? => true
max maximum value: (1..3).max => 3
min minimum value: `` (1..3).min => 1 ``
max_by value giving the greater block: (1..3).max_by {|a| 1.0/a } => 1
min_by value giving the smaller block: (1..3).min_by {|a| 1.0/a } => 3
minmax minimum and maximum value (1..3).minmax => [1, 3]
one? true if the block return true only once: (1..3).one? {|a| a==2 } => true
none? true if the block is always false (1..3).none? {|a| a==2 }=> false
reverse_each loops in reverse order: (1..3).reverse_each {|a| print a } => 321
sort sort elements: [3,2,1].sort => [1, 2, 3]
sort_by sorting based on the block: (1..3).sort_by {|a| 1.0/a } => [3, 2, 1]

flat_map : to build an array, by appending consecutive results of the block:

(1..2).flat_map{|a| [a,a+10,a+20]} => [1, 11, 21, 2, 12, 22]

group_by : to build an hash, the block gives the keys:

(1..3).group_by { |a| a+100 } => {101=>[1], 102=>[2], 103=>[3]}

minmax and sort with a block, giving a comparison expression which utilized the "<=>" operator:

(1..3).minmax {|a,b| 1.0/a <=> 1.0/b } => [3, 1]

(1..3).sort {|a,b| 1.0/a <=> 1.0/b } => [3, 2, 1]

Some iterator for numerics


upto 3.upto(5) {|i| print i, " " } => 3 4 5 (last value is included )

A Temptative Summary of the Ruby Language Pg. 29


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
downto 3.downto(1) {|n| print n, ".. " } => 3.. 2.. 1..
times 3.times {|n| print n, ".. " } => 0.. 1.. 2..
step 1.step(6, 2) {|i| print i, " " } => 1 3 5

If the block is missing these methods return an Enumerator object which can be converted to an array with
the to_a method

3.upto(5).to_a => [3, 4, 5]


3.downto(1).to_a => [3, 2, 1]
3.times.to_a => [0, 1, 2]
1.step(6, 2).to_a => [1, 3, 5]
12.2.step(14.0,0.5).to_a => [12.2, 12.7, 13.2, 13.7]

Some Iterators for Strings


each_char loops on characters: "abcd".each_char {|k| print k+"z" }azbzczdz=>
"abcd"
each_byte;bytes loops on bytes: "abcd".each_byte {|k| print k,"-" } =>
97-98-99-100-
eachy_line loops on lines (keep the final "n" characters)
upto loops on a sequence of strings: "a".upto("d"){|k| print k} => abcd

Some Iterators for Arrays


each gives each item to the block: [1,2,3].each {|k| print k} => 123
reverse_each gives items in reverse order: [1,2,3].each {|k| print k} => 123
each_index gives indexes to the block: [1,2,3].each_index {|k| print k} => 012
map array with block results: [1,2,3].map {|k| k+1} => [2,3,4]
collect;collect! array of block results: [1,2,3].collect {|i| i*i } => [1, 4, 9]
delete_if if block false deletes elements: [1,2,3].delete_if {|x| x.even?} => [1,
3]
keep_if keeps if block true: [1,2,3].keep_if { |x| x.even? } => [2]
select;select! elements with a true block: [1,2,3].select { |x| x.even? } => [2]
rindex index of element of first true block: [1,2,3].rindex {|k| k==2}=> 1
uniq ; uniq! elements with unique block value: [1,2,3,4].uniq {|k| k.even?}=> [1,2]

The creator of arrays can also be used as an iterator:


a=Array.new(3) { |i| i} => [0, 1, 2]

Some Iterators for Hashes


each ; gives each pair key,value {1=>"a",2=>"b"}.each {|k,v| print k,v} =>
each_pair 1a2b

A Temptative Summary of the Ruby Language Pg. 30


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
each_key gives the keys to the block: {1=>"a",2=>"b"}.each_key {|k| print k}
=>12
each_value gives the values to the block: {1=>"a",2=>"b"}.each_value{|k| print k}
=>ab
delete_if if block false deletes: {1=>"a",2=>"b"}.delete_if {|k,v| k==1 =>
{2=>"b"}
keep_if keeps if block true: {1=>"a",2=>"b"}.keep_if {|k,v| k==1 } =>
{1=>"a"}
select,select! hash of elements with true block: {1=>"a",2=>"b"}.select {|k,v|
k==1}{1=>"a"}

The merge method can be used associated with a block: when there are duplicated keys the block is
executed and the new value for the key is the the block result

{1=>"a",2=>"b"}.merge({1=>"x",3=>"z"}) {|key,v1,v2| v1+v2 } => {1=>"ax", 2=>"b", 3=>"z"}

Input/Output
The function: open returns a File object (if the filename begins with "|" it is a Unix named pipe):

f=open(filename,"access string")

access string:

"r:iso-8859-1" to read-only, for a specific encoding


"w+" read/write
"w" write only
"a" append to file, write only
"a+" append, read/write
"b" binary, to be added to the other codes: "wb" , "rb" ..

methods for file reading:

file.close() closes the file


a=f.gets gets the next line
a=f.readline
a=f.gets(10) gets 10 characters
a=f.gets("separator") gets a line, defined by an user-given line separator
a=gets next line from standard input
a=gets("separator")
a=f.getc gets next character
a=f.getbyte gets next byte
f.lineno returns the current line number
f.lineno=10 set the initial value of the line counter (file position unchanged)

A Temptative Summary of the Ruby Language Pg. 31


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
f.pos returns the file position (current byte)
a=f.readlines returns an array with the file lines
a=f.readlines("s") lines array, a line separator is given
f.each {|a| ..}
f.each_line {|a| ..} an iterator over the file lines
f.each("separator"){|a| ..} here a line separator is given
f.each_byte {|b| ..} an iterator over bytes
f.each_char {|b| ..} an iterator over characters

Useful methods of the File class:

File.exist?(filename) true if the file exists


File.file?(filename) tests if filename is a regular file
File.directory?(filename) tests if a directory
File.symlink?(filename) tests if filename is a symbolic link
, ,
File.size(filename) file size in bytes.
File.size?(filename) file size in bytes or nil if empty
File.zero?(filename) true if empty
, ,
File.readable?(filename) true if readable
File.writable?(filename) true if writable
File.executable?(filename) true if executable
File.world_readable?(filename) true if readable by everybody
File.world_writable?(filename) true if writable by everybody
, ,
File.ftype("/usr/bin/ruby") type of the file: "file", "directory", "link"
, ,
File.rename("newname", "oldname") renames a file
File.symlink("name", "link") makes a link
File.delete("test2") deletes a file
File.utime(atime, mtime, filename) changes access and modification time
File.chmod(0600, f) sets unix file permissions (octal argument)
. .
File.read("filename") reads and return the entire file as a string
File.read("filename", 4, 2) returns 4 bytes starting at byte 2
File.read("filename", nil, 6) returns from byte 6 to the end-of-file
linee = File.readlines("filename") return an array with the file lines

A Temptative Summary of the Ruby Language Pg. 32


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
File.foreach("filename") { } block looping on lines

putc, puts, print, write , examples:

o = STDOUT

o.putc(65) # writes the single byte 65 (capital A)


o.putc("B") # writes the single byte 66 (capital B)

o << x # print 'x'


o << x << y # print 'x' and 'y'

o.print s

o.printf fmt,*args # the printf function of C

o.puts # prints a newline


o.puts x # prints 'x', then a newline

o.write s # doesn't print a final newline

File random access:

f = File.open("test.txt")

f.pos # returns the current byte, same as: 'f.tell'


f.pos = 10 # set the position counter to 10

f.rewind # goes to the beginning of the file

f.seek(10) # go to byte 10, same as: 'f.seek(10, IO::SEEK_SET)'


f.seek(10, IO::SEEK_CUR) # skips 10 bytes from current position

f.eof? # tests if at end of file


f.closed? # tests if the file has been closed
f.tty? # tests if the stream is the interactive console

Ruby buffer management:

out=File.open('filename')
out.write("abcd")

out.flush # flush the Ruby output buffer for this stream

# to set the buffer mode:

out.sync = true # buffers are flushed after every write


out.sync = false # output is buffered by Ruby

out.sync # show the current buffer mode

out.fsync # flush the system buffers (not possible for some systems)

A Temptative Summary of the Ruby Language Pg. 33


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/
Modules
sintax:

module Nomemodulo # module definition

class ... # definition of a class in the module

end

def ... # definition of a function in the module

end

end

"include" mixes a module into the namespace of a class (use require before include if module in onother
file)
extend method insert a module into an instance

A Temptative Summary of the Ruby Language Pg. 34


By Marcello Galli -- version: 01-12-2014 15:51 - Downloaded from http://www.helldragon.eu/

You might also like