Sunteți pe pagina 1din 40

Web Application Architectures

Module 4: The Ruby Programming Language Lecture 1: Background

c 2011-13 G.L. Heileman

Module 4, Lecture 1

1/9

Ruby Programming Language


Rails was built using the Ruby programming language. Ruby code shows up in models:
class Post < ActiveRecord::Base end

views:
<%= @post.title %>

and controllers:
def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url } format.json { head :no_content } end end
c 2011-13 G.L. Heileman Module 4, Lecture 1 2/9

Ruby History
Yukihiro Matsumoto (Matz) created Ruby in the mid-1990s. I wanted a scripting language that was more powerful than Perl, and more OO than Python. Thats why I decided to design my own language. Matz developed Ruby with a focus on the programmer, rather than the machine. The design goal was to maximize programmer eciency (i.e., productivity), not the runtime eciency of the their programs. I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language.

c 2011-13 G.L. Heileman

Module 4, Lecture 1

3/9

Ruby Design
Matzs guiding philosophy for Ruby: Ruby is designed to make programmers happy. Ruby is designed according to the Principle of Least Astonishment the language should behave in a way that minimizes the confusion of experienced programmers (assuming youre experienced in Ruby, not operating with some other programming model in mind). Ruby is an object-oriented interpreted scripting language many nd it intuitive, exible and extensible. For more information, documentation and tutorials, visit: http://www.ruby-lang.org

c 2011-13 G.L. Heileman

Module 4, Lecture 1

4/9

Ruby Installation
Recall that to nd the version of Ruby youre running, use: $ ruby --version Ruby gems is a package management system. To see the gems you have installed, use: $ gem list Rails is a Ruby gem for building database-intensive web application frameworks. To install it, use: $ gem install rails

c 2011-13 G.L. Heileman

Module 4, Lecture 1

5/9

The Ruby Interpreter


Ruby is an interpreted language. You invoke the interpreter using the ruby command: Ex. $ ruby -e puts "Hello World!" Hello World! $ The -e prompt tells the interpreter to execute the line of Ruby code contained in the single quotes. Typically you will place your Ruby code in a le, with a .rb extension. E.g., put the previous code in the le hello.rb, and tell the interpreter to execute it using: $ ruby hello.rb Hello World! $
c 2011-13 G.L. Heileman Module 4, Lecture 1 6/9

The Ruby Interpreter


Interactive Ruby Shell (IRB) is an interpreter shell that allows you to execute Ruby code from a command prompt a REPL. Its very useful for debugging purposes. To open up a Ruby shell, type: $ irb 2.0.0p195 :001 > At the prompt provided by interactive ruby, you can type ruby expressions, and they will be evaluated: 2.0.0p195 :001 > 2+2 => 4 2.0.0p195 :002 >
c 2011-13 G.L. Heileman Module 4, Lecture 1 7/9

The Ruby Interpreter


You can invoke IRB from the root of a Rails application directory as follows:
$ rails console Loading development environment (Rails 4.0.0.rc1) 2.0.0-p195 :001 >

The Rails environment (including everything dened in the current Rails application) is loaded when you do this. You can directly manipulate your rails application from the console command line add/delete database items, inspect and manipulate object, etc. This is very useful, and common, way to debug Rails applications.

c 2011-13 G.L. Heileman

Module 4, Lecture 1

8/9

Language Features
Ruby is a multi-paradigm programming language: Scripting It can be used to write scripts that automate the execution of tasks within some environment. Imperative (procedure-oriented) programming It has the traditional control structures found in imperative programs. You can create functions with variables (that store state); however, dening functions/variables outside classes actually makes them methods of the root Object class. Object-oriented programming Everything is an object, derived from the Object class. Functional programming Computation proceeds via the evaluation of functions that depend only on their input, not the program state.

c 2011-13 G.L. Heileman

Module 4, Lecture 1

9/9

Web Application Architectures


Module 4: The Ruby Programming Language Lecture 2: Classes and Inheritance

c 2011-13 G.L. Heileman

Module 4, Lecture 2

1 / 10

Classes
Classes are dened using the keyword class followed by the name of the class. The name must begin with a capital, and the convention is to use CamelCase. To dene a method, use the keyword def: Ex. class MyClass @boo # an instance variable def my_method @foo = 2 # an instance variable end end > mc = MyClass.new > mc.my_method > mc.boo
c 2011-13 G.L. Heileman

# create a MyClass object # => 2 # => error


2 / 10

Module 4, Lecture 2

Methods
An instance variable can only be directly accessed or modied within a method denition. Ex. class MyClass def boo # a getter method return @boo end def boo=(val) # setter method @boo = val end end > mc = MyClass.new > boo = 1 # => 1 > boo # => 1
c 2011-13 G.L. Heileman

# create a MyClass object

Module 4, Lecture 2

3 / 10

Methods
Notice that there is no return value specied in the methods above. Ruby methods have implicit return values the value of the last expression executed in a method is its return value. The return statement still exists, but you dont need to use it. Ex. def min(x,y) if x < y then x else y end end When invoking a method, parentheses are optional.

c 2011-13 G.L. Heileman

Module 4, Lecture 2

4 / 10

Class Methods
Class methods are created in the same way as normal methods, except they are prexed by the keyword self. Ex. class MyClass def self.cls_method "MyClass type" end end > MyClass.cls_method # => "MyClass type"

c 2011-13 G.L. Heileman

Module 4, Lecture 2

5 / 10

Methods
In Ruby the last character of a method name is often used to indicate its behavior: If the method ends with a question mark it indicates that the return value is boolean. If the method ends with an exclamation, it indicates that the method can change the state of the object. In the previous case, it is common to also provide a non-exclamation version of the method, which indicates that the modies a copy of the object. The keyword self can be used inside an objects methods in order to refer to the current object.

c 2011-13 G.L. Heileman

Module 4, Lecture 2

6 / 10

Inheritance, Mixins and Extending Classes


Only single inheritance is supported; however, the mixin capability associated with modules basically gives you multiple inheritance. Classes are never closed, you can always add methods to an existing class.
This applies to the classes you write as well as the standard, built-in classes. You simply open up a class denition for an existing class, and the new contents you specify will be added to whatevers already dened for that class. Ex. class Fixnum def previous return self-1 end end
c 2011-13 G.L. Heileman Module 4, Lecture 2 7 / 10

Specifying Access
Within a class denition you may specify access levels using the keywords public, private and protected. The behavior is a little dierent than in C++ or Java:
public no access control, can be called by anyone. protected can be invoked only by objects of the dening class and its subclasses. private can only be called in the context of the current object, without on object reference on the LHS, i.e, two objects of the same class cannot invoke each others private methods. Thus, the receiver of a private method is always self.

By default, every method in a class is public, and every instance variable is protected.

c 2011-13 G.L. Heileman

Module 4, Lecture 2

8 / 10

Accessors
There is a shorthand way of providing accessors for an objects attributes:
class Person attr_accessor :first_name, :last_name end

will create attributes (instance variables) for first_name and last_name, as well as getter and setter methods for each. If you only want a getter method, use attr_reader, and if you only want a setter, use attr_writer

c 2011-13 G.L. Heileman

Module 4, Lecture 2

9 / 10

Inheritance
The syntax for inheritance is: class NewClass < SuperClass ... end The initialize method, which is always private, is used to create a constructor that is invoked by calling new on a class name. E.g., a = Array.new You can create a module with its own namespace by using the keyword module, and include a number of classes within it. You can include a module within another program by using the keywork require, e.g., require module_name Within a class, you use the keyword include to mixin a module. This makes all of the methods dened in that module a part of the class that includes the module.
c 2011-13 G.L. Heileman Module 4, Lecture 2 10 / 10

Web Application Architectures


Module 4: The Ruby Programming Language Lecture 3: Objects and Variables

c 2011-13 G.L. Heileman

Module 4, Lecture 3

1/5

Objects
Everything is Ruby is an object, the Object class is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden. An important method in the Object class is class(). It returns the type of an object. > > > > 1.class() 1.class 1.0.class "Foo".class # # # # => => => => Fixnum Fixnum Float String

Notice how parentheses are optional they are commonly omitted. The language syntax is sensitive to the capitalization of identiers, in most cases treating capitalized variables as constants.
c 2011-13 G.L. Heileman Module 4, Lecture 3 2/5

Variables
Ruby does not use variable declarations, if you assign a value to a literal, an appropriate variable named after that literal is created. Ex. > a = 2 > a # => 2 # => 2

In this example, a has type Fixnum, this is an integer data in Ruby. The other integer type is Bignum (represents numbers of arbitrary size). Ex. > a = "2" > a Now a is a String variable.
c 2011-13 G.L. Heileman Module 4, Lecture 3 3/5

# => "2" # => "2"

Variables
Important: All assignments are done by reference in Ruby. I.e, a variable just holds a reference to an object, and does not care about the type of the object. Ruby supports parallel assignment. Ex. You can easily swap the values stored in two variables: > a = 2 > b = 1 > puts a, b # # # # # # => => 2 1 => => 2 1

a, b = b, a

nil [1, 2]

c 2011-13 G.L. Heileman

Module 4, Lecture 3

4/5

Variables
Ruby uses simple naming conventions to denote the scope of variables:
name could be a local variable. @name an instance variable. @@name a class variable. $name a global variable.

The @ and $ sigils enhance readability by allowing the programmer to easily identify the roles of each variable. Furthermore, local variables must begin with a lowercase letter, and the convention is to use underscores, rather than camel case, for multi-word names. Constants are any name that starts with an uppercase letter, and the convention is to use underscores. Classes and modules are treated as constants, so they begin with uppercase letters, and the convention is to use camel case.

c 2011-13 G.L. Heileman

Module 4, Lecture 3

5/5

Web Application Architectures


Module 4: The Ruby Programming Language Lecture 4: Strings, Regular Expressions and Symbols

c 2011-13 G.L. Heileman

Module 4, Lecture 4

1/8

Strings
You can create string literals in Ruby using either single or double quotes. You can do a little bit more with double quoted strings. E.g., you can insert arbitrary Ruby expressions using string interpolation. Ex. > "360 degrees=#{2*Math::PI} radians" => "360 degrees=6.283185307179586 radians" If you enclose a string in single backquotes (backticks), the string will be executed as a command in the underlying OS. Ex. > date => "Tue Oct 15 09:10:21 MDT 2013\n"
c 2011-13 G.L. Heileman Module 4, Lecture 4 2/8

Strings
Strings in Ruby are mutable, as in C/C++, but unlike Java. Thus, each time Ruby encounters a new string literal, it create a new String object. I.e, if youre creating a string literal within a loop, each iteration will create a new String object. The Ruby String class contains a number of methods which can be used to manipulate strings. Ex. > > > > > > name = "Homer Blimpson" # => "Homer Blimpson" name.length # => 14 name[6] # => "B" name[6..14] # => "Blimpson" "Bart " + name[6..14] # => "Bart Blimpson" name.encoding # => #<Encoding:UTF-8>
Module 4, Lecture 4 3/8

c 2011-13 G.L. Heileman

Regular Expression Class


Ruby has a regular expression class, called Regexp, that is closely related to strings. A regular expression provides a concise and exible means for matching strings of text, such as particular characters, words, or patterns of characters. In Ruby, a regular expression is written in the form of: /pattern/modifiers where pattern is the regular expression itself, and modiers are a series of characters indicating various options. The modiers part is optional. This syntax is borrowed from Perl. To test if a particular Regex matches (part of) a string, use the = operator. This operator returns the character position in the string of the start of the match (which evaluates to true in a boolean test), or nil if no match was found (which evaluates to false). Ex. "Homer" =~ /er/ # => 3
c 2011-13 G.L. Heileman Module 4, Lecture 4 4/8

Regular Expressions
The following have special meanings in patterns: meaning [ ] range specication, e.g., [a-z] means a letter between a and z \w word character, same as [0-9A-Za-z_] \W non-word character \s space character, same as [\t\n\r\f] \S non-space character \d digit character, same as [0-9] \D non-digit character \b backspace (if used in a range specication) \b word boundary (if not used in a range specication) \B non-word boundary * zero or more repetitions of the preceding + one or more repetitions of the preceding {m,n} at least m and at most n repetitions of the preceding ? at most one repetition of the preceding, same as {0,1} | either preceding or next expression may match ( ) grouping
c 2011-13 G.L. Heileman Module 4, Lecture 4 5/8

Regular Expressions
The preceding table only contained a partial list of the special characters that can be used in a Ruby regular expression. Consult a Ruby reference for more details. Regular expression are often used to process strings. Ex. The following Ruby expression will replace all of the non-digit characters in phone with "". I.e., it will strip everything out of the phone number, except digits: phone = phone.gsub!(/\D/, "") Regular expression are commonly used to validate emails, phone numbers, and other user-supplied input. Ex. The following regular expression can be used to validate email addresses: /\A[\w\._%]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/ (Note: We didnt cover all of the characters used in this regular expression.)
c 2011-13 G.L. Heileman Module 4, Lecture 4 6/8

Symbols
Ruby symbols are also closely related to strings. A Ruby interpreter maintains a symbol table where it stores the names of all classes, methods and variables. You can add your own symbols to this table. Specically, a symbol is created if you precede a name with a colon. Ex. attr_reader :row, :col Ruby symbols are used to represent names and strings; however unlike String objects, symbols of the same name are initialized and exist in memory only once during a Ruby session. Ruby symbols are immutable, and cannot be modied during runtime. Ex. :name = "Homer"
c 2011-13 G.L. Heileman

# => will yield an error


Module 4, Lecture 4 7/8

Symbols
Theres a big space advantage associated with symbols, as each unique is only stored once in memory. Multiple strings with the same name my exist in memory. Ex.
> > > > puts puts puts puts :name.object_id :name.object_id "name".object_id "name".object_id # # # # => => => => yields yields yields yields 20488 20488 2168472820 2168484060

When should you use a string and when should you use a symbol? General rules of thumb:
If the contents (i.e., the sequence of characters) of the object is important, e.g., if you need to manipulate these characters, use a string. If the identity of the object is important (in which case you probably dont want to manipulate the characters), use a symbol.
c 2011-13 G.L. Heileman Module 4, Lecture 4 8/8

Web Application Architectures


Module 4: The Ruby Programming Language Lecture 5: Expressions and Control Structures

c 2011-13 G.L. Heileman

Module 4, Lecture 5

1/6

Expressions
The Ruby syntax is expression-oriented. Everything in Ruby is treated as an expression and therefore evaluates to something. Ex. Control structures for conditional execution or looping, which would be treated as statements in other languages, are treated as expressions in Ruby. In Ruby, if, case and for structures return the value of the last expression evaluated within the structure.

c 2011-13 G.L. Heileman

Module 4, Lecture 5

2/6

Control Structures Conditional Execution


Ruby has a rich syntax for expressing conditionals the most basic is: if expression code end where code is executed if and only if the conditional expression evaluates to something other than false or nil. Else clauses can be added to specify code that should be executed if the conditional expression is not true:
if expression1 code elsif expression2 code else code end
c 2011-13 G.L. Heileman Module 4, Lecture 5 3/6

Control Structures Conditional Execution


Theres a shorthand way of expressing the if conditional that treats it as an expression modier: code if expression Ruby also has a ?: operator, as in C/C++. Comparison operators: ==, !=, =, !, === There is a case structure in Ruby, === is the case-equality operator.

c 2011-13 G.L. Heileman

Module 4, Lecture 5

4/6

Control Structures Conditional Execution


In addition to the standard set of conditionals, Ruby has added some that are intended to increase the readability/understandability of code. E.g., the following is the opposite of an if statement: until expression code end where code is executed until the conditional expression evaluates to something other than false or nil. You cannot attach else clauses to the until conditional.

c 2011-13 G.L. Heileman

Module 4, Lecture 5

5/6

Control Structures Iteration


The for/in loop iterates over an enumerable collection: for var in collection do body end Exit condition loop: while condition do body end Exit condition loop, opposite of while: until condition do body end In Ruby, its more common to use iterators (next lecture).
c 2011-13 G.L. Heileman Module 4, Lecture 5 6/6

Web Application Architectures


Module 4: The Ruby Programming Language Module Overview

c 2011-13 G.L. Heileman

Module 4: Overview

1/2

Module Overview
Background Classes and Inheritance Objects and Variables Strings, Regular Expressions and Symbols Expressions and Control Structures Collections, Blocks and Iterators

c 2011-13 G.L. Heileman

Module 4: Overview

2/2

S-ar putea să vă placă și