

Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Os melhores documentos à venda: Trabalhos de alunos formados
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Comunidade
Peça ajuda à comunidade e tire suas dúvidas relacionadas ao estudo
Descubra as melhores universidades em seu país de acordo com os usuários da Docsity
Guias grátis
Baixe gratuitamente nossos guias de estudo, métodos para diminuir a ansiedade, dicas de TCC preparadas pelos professores da Docsity
As regras básicas de sintaxe do ruby, incluindo palavras-chave reservadas, tipos de dados, strings e expressões. Além disso, aborda backslashes, here docs, ranges, classes, arrays, hashes, variáveis e constantes, predefinidos globais e constantes. O documento também inclui informações sobre modos de arquivos, alias, proc objects, exceções e copyright.
O que você vai aprender
Tipologia: Esquemas
1 / 2
Esta página não é visível na pré-visualização
Não perca as partes importantes!
used so often.
In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!, %@@, etc.
\f (form feed), \b (backspace), \a (bell), \e (escape), \s (whitespace), \nnn (octal),\xnn (hexadecimal), \cx (control x), \C-x (control x), \M-x (meta x), \M-\C-x (meta control x)
<<"identifier"<<'identifier' # interpolation# no interpolation <<-identifier<<-"identifier" # interpolation, indented end # interpolation, indented end <<-'identifier' # no interpolation, indented end
'a'..'z'(1..10) === 5 -> true (1..10) === 15 -> false
while gets endprint if /start/../end/ class RangeThingy
def <=>(rhs) end# ... def succ# ... endend range = RangeThingy.new(lower_bound) .. RangeThingy.new(upper_bound)
/normal regex/[xim]%r|alternate form|[xim] Regex.new(pattern, options)
%w(foo bar baz)%W(foo #{bar} baz) # no interpolation# interpolation Indexes may be negative, and they index backwards (-1 is the last element).
{ expr => expr, ... }
Common methods include:
@instance_variable[OtherClass::]CONSTANT local_variable
Comments start with a pound/sharp (#) character and go to EOL. Lines between ‘=begin’ and ‘=end’ are skipped by the interpreter. Ruby programs are sequence of expressions. Each expression is delimited by semicolons (;) or newlines unless obviously incomplete (e.g. trailing ‘+’). Backslashes at the end of line does not terminate expression.
alias and BEGIN begin break case class def defined do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
123 1_234 123.45 1.2e- 0xffff (hex) 0b01011 (binary) 0377 (octal) ?a ASCII character ?\C-a Control-a ?\M-a Meta-a ?\M-\C-a Meta-Control-a
'no interpolation' "#{interpolation} and backslashes\n" %q(no interpolation) %Q(interpolation and backslashes) %(interpolation and backslashes) echo command interpretation with interpolation and backslashes
%x(echo command interpretation with interpolation and backslashes)
. any character except newline [set] any single character of set [^set] any single character NOT of set
File.join(p1, p2, ... pN) => “p1/p2/.../pN© platform independent paths File.new(path, mode_string="r") => file File.new(path, mode_num [, perm_num]) => file File.open(filename, mode_string="r") {|file| block} -> nil File.open(filename [, mode_num [, perm_num ]]) {|file| block} -> nil IO.foreach(path, sepstring=$/) {|line| block} IO.readlines(path) => array
r Read-only, starts at beginning of file (default mode). r+ Read-write, starts at beginning of file. w Write-only, truncates existing file to zero length or creates a new file for writing. w+ Read-write, truncates existing file to zero length or creates a new file for reading and writing. a Write-only, starts at end of file if file exists, otherwise creates a new file for writing. a+ Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing. b Binary file mode (may appear with any of the key letters listed above). Only necessary for DOS/Windows.
self the receiver of the current method nil the sole instance of NilClass (represents false) true the sole instance of TrueClass (typical true value) false the sole instance of FalseClass (represents false) FILE the current source file name. LINE the current line number in the source file.
$! The exception information message set by ‘raise’. $@ Array of backtrace of the last exception thrown. $& The string matched by the last successful pattern match in this scope. $` The string to the left of the last successful match. $' The string to the right of the last successful match. $+ The last bracket matched by the last successful match. $1 The Nth group of the last successful match. May be > 1. $~ The information about the last match in the current scope. $= The flag for case insensitive, nil by default. $/ The input record separator, newline by default. $\ The output record separator for the print and IO#write. Default is nil. $, The output field separator for the print and Array#join. $; The default separator for String#split. $. The current input line number of the last file that was read. $< The virtual concatenation file of the files given on command line. $> The default output for print, printf. $stdout by default. $_ The last input line of string by gets or readline. $0 Contains the name of the script being executed. May be assignable. $* Command line arguments given for the script sans args. $$ The process number of the Ruby running this script. $? The status of the last executed child process. $: Load path for scripts and binary modules by load or require. $" The array contains the module names loaded by require. $DEBUG The status of the -d switch. $FILENAME Current input file from $<. Same as $<.filename. $LOAD_PATH The alias to the $:. $stderr The current standard error output. $stdin The current standard input. $stdout The current standard output. $VERBOSE The verbose flag, which is set by the -v switch. $-0 The alias to $/.
Pre-defined Global Constants
Expressions Terms Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant reference, ormethod invocation.
Operators and Precedence
Control Expressions if bool-expr [then]body elsif bool-expr [then]body elsebody end unless bool-expr [then]body else endbody expr if bool-expr expr unless bool-expr case target-expr
when comparison [, comparison]... [then]body when comparison [, comparison]... [then]body [else... endbody] while bool-expr [do]body end until bool-expr [do]body end beginbody end while bool-expr begin end until bool-exprbody for name[, name]... in expr [do] endbody expr.each do | name[, name]... |body end expr while bool-exprexpr until bool-expr
Invoking a Method Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow. Here are some examples:
callparams := ( [param]* [, hash] [*arr] [&proc] ) := [receiver ('::' | '.')] name [params] [block] block := { body } | do body end
Defining a Class Class names begin with capital characters. class Identifier [ < Superclass ]; ... ; end
class << obj; ...; end
Defining a Module Module names begin with capital characters. module Identifier; ...; end Defining a Method def method_name(arg_list); ...; end def expr.method_name(arg_list); ...; end
Access Restriction
Restriction used without arguments set the default access control. Used with arguments, sets the access of the named
methods and constants. class A protecteddef protected_method; ...; end endclass B < A public def test_protectedmyA = A.new endmyA.protected_method endb = B.new.test_protected
Module provides the following utility methods:
Aliasing alias
Proc Objects See class Proc for more information. Created via: Kernel#proc (or Kernel#lambda) Proc#new&block argument on a method
Exceptions begin [ rescue [ exception_class [ => var ], ... ]expr [ elseexpr ] expr ] [ ensureexpr ] end raise [ exception_class, ] [ message ] The default exception_class for rescue is StandardError, not Exception. Raise without an exception_class raises aRuntimeError. All exception classes must inherit from Exception or one of its children (listed below).
Catch and Throw catch :label do expr endthrow :label Copyright © 2005 Ryan Davis with Austin Ziegler. PDF version by Austin Ziegler. Licensed under the
$-a True if option -a is set. Read-only variable. $-d The alias to $DEBUG. $-F The alias to $;. $-i In in-place-edit mode, this variable holds the extention, otherwise nil. $-I The alias to $:. $-l True if option -l is set. Read-only variable. $-p True if option -p is set. Read-only variable. $-v The alias to $VERBOSE.
TRUE The typical true value. FALSE The false itself. NIL The nil itself. STDIN The standard input. The default value for $stdin. STDOUT The standard output. The default value for $stdout. STDERR The standard error output. The default value for $stderr. ENV The hash contains current environment variables. ARGF The alias to the $<. ARGV The alias to the $*. DATA The file object of the script, pointing just after END. RUBY_VERSION The ruby version string (VERSION was depricated). RUBY_RELEASE_DATE The relase date string. RUBY_PLATFORM The platform identifier.
<< >> & | ^
= < <= <=> == === != =~ !~ && || .. ... = (+=, -=, ...) not and or
break terminates loop immediately. redo immediately repeats w/o rerunning the condition. next starts the next iteration through the loop. retry restarts the loop, rerunning the condition.
method obj.method Class::method method(arg1, arg2) method(arg1, key1 => val1, key2 => val2, aval1, aval2) { block } method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3)
arg_list := ['('] [varname] ['' listname] ['&' blockname] [')'] Arguments may have default values (varname = expr). Method definitions may not be nested. method_name may be an operator: <=>, ==, ===, =~, <, <=, > >=, +, -, *, /, %, **, <<, >>, ~, +@, -@, [], []= (the last takes two arguments)
public totally accessable. protected accessable only by instances of class and direct descendants. Even through hasA relationships. (see below) private accessable only by instances of class.
attr_reader
Creates a read-only accessor for each
Creates a write-only accessor for each
Equivalent to "attr_reader
Equivalent to "attr
Blocks are full closures, remembering their variable context. Blocks are invoked via yield and may be passed arguments. Block arguments may not have default parameters. Brace form ({/}) has higher precedence and will bind to the last parameter if the invocation is made without parentheses. do/end form has lower precedence and will bind to the invocation even without parentheses.
StandardError LocalJumpError, SystemStackError, ZeroDivisionError, RangeError (FloatDomainError), SecurityError, ThreadError, IOError (EOFError), ArgumentError, IndexError, RuntimeError, TypeError, SystemCallError (Errno::*), RegexpError SignalException Interrupt NoMemoryError ScriptError LoadError, NameError, SyntaxError, NotImplementedError SystemExit