Está en la página 1de 52

Ruby: An Introduction

Jorge Chao
University of New Orleans

Slides available as PDF @


www.cs.uno.edu/~jchao/RubyIntro.pdf

Thursday, April 28, 2011


Matz
• The Ruby Godfather

Thursday, April 28, 2011


Some Ruby History
• Ruby was developed in 1993 by Yukihiro
“Matz” Matsumoto.
• His intention was to create “a scripting
language more powerful than Perl, and
more object-oriented than Python.”
• Bonus: Unlike Perl, you code doesn’t look
like a giant regular expression when you’ve
finished.

Thursday, April 28, 2011


What is Ruby?

• Ruby is an Object Oriented scripting


language
• In Ruby, everything is an object
• There is no notion of a primitive in Ruby, as
in Java.

Thursday, April 28, 2011


irb
• Interactive Ruby Shell. All of the terminal
screenshots in this presentation are from
irb. Its the best way to prototype and
informally test your code.

Thursday, April 28, 2011


Really Object Oriented

Thursday, April 28, 2011


Really Object Oriented
• No need to declare variables beforehand.


Thursday, April 28, 2011
Dynamic Typing

• Sometimes called ‘Duck Typing’ or ‘Lazy


Typing,’ if you’re a meanie.
• If it looks like a duck, quacks like a duck,
then it’s a duck.
• The interpreter will assign types to
variables dynamically based on context.

Thursday, April 28, 2011


Dynamic Typing
• This also means the interpreter can
allocate more memory for a variable.


Thursday, April 28, 2011
Built-in Types
• Numbers are represented by either the
Fixnum, Bignum or Float types (all children of
Numeric).
• Fixnum holds 32-bit Integer values
• Fixnum overflows upconvert to Bignum,
which is considered an infinite-length
bitstring with 2’s compliment notation.
• Float is used for representing real numbers.
Thursday, April 28, 2011
Numbers
• Basic Numeric Operations

Thursday, April 28, 2011


Numbers
• In Ruby, the analog to the incrementor
operator in C or Java, i++, is i += 1.
• This can be done for any basic arithmetic
operation.


Thursday, April 28, 2011
Numbers
• Ruby makes an object of type Float any
time a decimal point is used.
• The number must have a digit following the
decimal, as Ruby can perform class
operations on numbers.
• Ruby implicitly casts the result of an
arithmetic operation between a Float and a
Fixnum to a Float.

Thursday, April 28, 2011


Strings
• Ruby has great built in String manipulation
facilities. Dots, dots everywhere.


Thursday, April 28, 2011
Strings
• Incomplete list of built in String functions
• % * + << <=> == =~ capitalize
center chomp chop concat count crypt
delete downcase dump each empty?
end_regexp eql? gsub hash include?
index insert intern is_complex_yaml?
length match oct quote replace reverse
scan scanf size slice split squeeze strip
sub swapcase to_f to_i to_s to_str
to_sym to_yaml tr tr_s upcase upto
Thursday, April 28, 2011
Data Structures

• Arrays and Hashes


• Arrays can be initialized empty, or with
values.
• Arrays can be combined using the +
operator or array.concat(other_array)

Thursday, April 28, 2011


Arrays
• Basic array manipulation


Thursday, April 28, 2011
Hashes
• Some basic hash manipulation, notice the use
of :symbols, I’ll cover them in a minute.


Thursday, April 28, 2011
Iterators
• What would collections of things be if we
couldn’t iterate over them?
• Most iteration in Ruby is done using a do
block.
• All iterations in Ruby are accomplished by
passing callback closures to container
methods.

Thursday, April 28, 2011


Iteration Examples
• Collection.each
• Similar to a foreach loop.

Thursday, April 28, 2011


More Iterators
• Fixnum.times and Range.each can be used
to iterate a fixed number of times, similar
to a for (i = 0; i < 10; i++) construct.


Thursday, April 28, 2011
Classes
• Classes start with the class keyword, end
them with...end.

Thursday, April 28, 2011


Using my_class.rb
• Load the newly created class into irb, and
test its functionality.


Thursday, April 28, 2011
Essence Vs. Ceremony
• An idea from Stu Halloway at Relevance Inc.
• “Good Code is the opposite of legacy
code: it captures and communicates essence
while omitting ceremony (irrelevant detail).”
• The design philosophy of the language
determines what kind of code you write
with it.

Thursday, April 28, 2011


Essence Vs. Ceremony

• Ceremony is code unrelated to the task at


hand. Ceremony is found everywhere:
• Factory Patterns (Java)

• Getters and setters (Java)

• Verbose exception handling (Java)

• Special syntax for class and instance variables (Ruby)

• Special syntax for ALL types of variables (Perl %$@, etc.)

Thursday, April 28, 2011


Ruby != Java
• Writing Ruby with Java like ceremony.

Thursday, April 28, 2011


This Time With Feeling
• The same thing for less.
• Making readers and writers for attributes.

Thursday, April 28, 2011


Accessors
• Assessors in Ruby enforce the Uniform
Access Principle which states: “All services
offered by a module should be available
through a uniform notation, which does not
betray its implementation.”
• :attr_accessor creates getters and setters
for instance variables, preventing direct
access to them. Its good to stay DRY.

Thursday, April 28, 2011


Blocks and Closures
• Lets make our own iterator:

Thursday, April 28, 2011


Blocks and Closures
• In the Array.iterate! example, the Array
object was extended at runtime with new
functionality.
• When iterate! is called on array in this
block context, when the yield statement is
reached it passes the code (and variable) in
the block to the method.

Thursday, April 28, 2011


yield Example
• A Lotus Notes Domino email server led to
this next example:

Thursday, April 28, 2011


yield for Layouts
• Rails uses yield to insert your page content
inside a page layout.

Thursday, April 28, 2011


Symbols
• What is a symbol? The variable name
passed to the attr_accesor and the variable
used in the hash example are both symbols.
• Symbols in Ruby always start with a :
• :a_symbol
• Why use symbols?

Thursday, April 28, 2011


Why Symbols?
• :symbols are defined as a way to efficiently
have descriptive names while saving the
space one would use to generate a string
for each naming instance.
• In Ruby, and much more in Rails, symbols
will be used to identify constructs that are
used frequently (HTTP :get comes to mind)

Thursday, April 28, 2011


Oh! The Savings!
• :symbols are a great way to conserve
memory


Thursday, April 28, 2011
More on Symbols
• Kevin Clark, Ruby Developer says:
• “The intention of symbols are for
identification of (user-level, primarily)
constructs: a slot in a hash, a method, an
option, etc.”
• That’s the great thing about symbols, they
can refer to variables or methods.

Thursday, April 28, 2011


Object Reflection

• Object reflection: “The process by which a


program can observe (type introspection)
and modify its own structure and behavior
at runtime.”
• Reflection allows inspection of classes,
inheritance hierarchies, methods, etc.
without prior knowledge.

Thursday, April 28, 2011


Object Reflection

• Reflection also allows instantiation of new


objects and invocation of methods.
• How does Ruby handle reflection?
• Let’s look at how we would do it in C or
Java first.

Thursday, April 28, 2011


Dispatch Table in C

Thursday, April 28, 2011


Reflection, Java Style

Thursday, April 28, 2011


Reflective Rubies
• Create instance methods in a module or
helper class


Thursday, April 28, 2011
Using Object.send
• Object.send takes a symbol or string as
parameter.


Thursday, April 28, 2011
More on Reflection

• respond_to?(method) checks if a class or


instance can call the method passed
• kind_of?(object) checks if the class or
instance is of that type (inheritance too!)
• instance_of?(object) checks if the caller is
of that particular type.

Thursday, April 28, 2011


Examples
• Some examples of querying an instance
about itself

Thursday, April 28, 2011


More Object Inspection
• Some other helpful inspection methods

Thursday, April 28, 2011


Inheritance Inspection
• superclass and ancestors work differently

Thursday, April 28, 2011


Inheritance
• Inheritance works as you would expect in
an object-oriented language.

Thursday, April 28, 2011


Testing Inheritance
• Same as it ever was.

Thursday, April 28, 2011


Documentation as a
Ransom Note

Thursday, April 28, 2011


Ruby Documentation
• Some resources for great Ruby
documentation:
• http://www.ruby-doc.org/core/
• Ruby Homepage:
• http://www.ruby-lang.org/en/
• Ruby tutorial as told by foxes:
• http://poignantguide.net/ruby/
Thursday, April 28, 2011
Finally
• An example of a Ruby tutorial on the web
(why’s poignant guide to Ruby)

Thursday, April 28, 2011


Thanks for Listening

• Next time we’ll see if Rails is really worth


the hype (spoiler: it is).

Thursday, April 28, 2011

También podría gustarte