Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ruby. What is Ruby? Programming Language Object-oriented Interpreted Popular- Ruby on Rails a framework for Web Server Programming.

Similar presentations


Presentation on theme: "Ruby. What is Ruby? Programming Language Object-oriented Interpreted Popular- Ruby on Rails a framework for Web Server Programming."— Presentation transcript:

1 Ruby

2 What is Ruby? Programming Language Object-oriented Interpreted Popular- Ruby on Rails a framework for Web Server Programming

3 Interpreted Languages Not compiled like Java Code is written and then directly executed by an interpreter Type commands into interpreter and see immediate results Computer Runtime Environment CompilerCode Java: ComputerInterpreterCode Ruby:

4 What is Ruby on Rails (RoR) Development framework for web applications written in Ruby Used by some of your favorite sites!favorite sites

5 Advantages of a framework Standard features/functionality are built-in Predictable application organization Easier to maintain Easier to get things going

6 Installation Windows Navigate to: http://www.ruby-lang.org/en/downloads/http://www.ruby-lang.org/en/downloads/ Scroll down to "Ruby on Windows" Download the "One-click Installer" Follow the install instructions Include RubyGems if possible (this will be necessary for Rails installation later) Mac/Linux OS X 10.4 ships with broken Ruby! Go here… http://hivelogic.com/articles/view/ruby-rails-mongrel-mysql-osx

7 hello_world.rb puts "hello world!" All source code files end with.rb = ruby NOTE: we are not really going to learn how to make general ruby programs but, in this class we will learn about Ruby on Rails ---which is a web framework for making web apps or web sites.

8 puts vs. print "puts" adds a new line after it is done analogous System.out.println() "print" does not add a new line analogous to System.out.print()

9 Running Ruby Programs (via interpreter) Use the Ruby interpreter ruby hello_world.rb “ruby” tells the computer to use the Ruby interpreter Interactive Ruby (irb) console irb Get immediate feedback Test Ruby features NOTE: we are not really going to learn how to make general ruby programs but, in this class we will learn about Ruby on Rails --- which is a web framework for making web apps or web sites.

10 Comments # this is a single line comment =begin this is a multiline comment nothing in here will be part of the code =end

11 Variables Declaration – No need to declare a "type" Assignment – same as in Java Example: (like javascript) x = "hello world"# String y = 3# Fixnum z = 4.5# Float r = 1..10# Range

12 Variable Names and Scopes foo Local variable $foo Global variable @foo Instance variable in object @@foo Class variable MAX_USERS “Constant” (by convention)

13 Difference between instance and “class” variables Instance variables are scoped within a specific instance. instance variable title, each post object will have its own title. Class variables, instead, is shared across all instances of that class. class Post def initialize(title) @title = title end def title @title end p1 = Post.new("First post") p2 = Post.new("Second post") p1.title # => "First post" p2.title # => "Second post" class Post @@blog = "The blog“ # previous stuff for title here……. def blog @@blog end def blog=(value) @@blog = value end p1.blog # => "The blog" p2.blog # => "The blog“ p1.blog = "New blog" p1.blog # => "New blog" p2.blog # => "New blog"

14 Objects Everything is an object. Common Types (Classes): Numbers, Strings, Ranges nil, Ruby's equivalent of null is also an object Uses "dot-notation" like Java objects You can find the class of any variable x = "hello" x.class  String You can find the methods of any variable or class x = "hello" x.methods String.methods

15 String Literals “How are you today?”

16 Single quotes (only \' and \\ ) 'Bill\'s "personal" book' Double quotes (many escape sequences) "Found #{count} errors\nAborting job\n" %q (similar to single quotes) %q Hello > %Q (similar to double quotes) %Q|She said "#{greeting}"\n| “Here documents” <<END First line Second line END Ruby String Syntax

17 Equalities

18 x = Array.new # how to declare an array x << 10 x[0] = 99 y = ["Alice", 23, 7.3] x[1] = y[1] + y[-1] ary = Array.new #sets to empty array [] Array.new(3) #sets to length of 3 [nil, nil, nil] Array.new(3, true) #sets to length of 3 [true, true, true] person = Hash.new person["last_name"] = "Rodriguez" person[:first_name] = "Alice“ order = {"item" => "Corn Flakes", "weight" => 18} order = {:item => "Corn Flakes", :weight => 18} order = {item: "Corn Flakes", weight: 18} Arrays and Hashes

19 Hashes – Starting the Zombies example From http://railsforzombies.org/http://railsforzombies.org/

20 Arrays ---accessing elements arr = [1, 2, 3, 4, 5, 6] arr[2] # 3 arr[100] # nil arr[-3]# 4 arr[2, 3] # [3, 4, 5] –means start index 2 and get 3 elements arr[1..4] # [2, 3, 4, 5] –means start index 1 through 4 index Also, arr.first and arr.last array = [14, 22, 34, 46, 92] for value in array do... end

21 Objects (cont.) There are many methods that all Objects have Include the "?" in the method names, it is a Ruby naming convention for boolean methods nil? eql?/equal? ( 3.eql?2 ) ==, !=, === instance_of? is_a? to_s

22 Numbers Numbers are objects Different Classes of Numbers FixNum, Float 3.eql?2  false -42.abs  42 3.4.round  3 3.6.round  4 3.2.ceil  4 3.8.floor  3 3.zero?  false

23 Boolean nil or false = false Everything else = true

24 String Methods "hello world".length  11 "hello world".nil?  false "".nil?  false "ryan" > "kelly"  true "hello_world!".instance_of?String  true "hello" * 3  "hellohellohello" "hello" + " world"  "hello world" "hello world".index("w")  6

25 Operators and Logic Same as Java *, /, +, - Also same as Java "and" and "or" as well as "&&" and "||" Strings String concatenation (+) String multiplication (*)

26 Conditionals: if/elsif/else/end Must use "elsif" instead of "else if" Notice use of "end". It replaces closing curly braces in Java Example: if (age < 35) puts "young whipper-snapper" elsif (age < 105) puts "80 is the new 30!" else puts "wow… gratz..." end

27 Inline "if" statements Original if-statement if age < 105 puts "don't worry, you are still young" end Inline if-statement puts "don't worry, you are still young" if age < 105

28 Case Statements grade = case score when 0..60: ‘F’ when 61..70: ‘D’ when 71..80: ‘C’ when 81..90: ‘B’ when 90..100: ‘A’ end

29 for-loops for-loops can use ranges Example 1: for i in 1..10 puts i end

30 for-loops and ranges You may need a more advanced range for your for-loop Bounds of a range can be expressions Example: for i in 1..(2*5) puts i end

31 Out of blocks or loops: break, redo, next, retry

32 while-loops Cannot use "i++" Example: i = 0 while i < 5 puts i i = i + 1 end

33 Example little routine sum = 0 i = 1 while i <= 10 do sum += i*i i = i + 1 end puts "Sum of squares is #{sum}\n" Newline is statement separator do... end instead of {... } Optional parentheses in method invocation Substitution in string value No variable declarations

34 unless "unless" is the logical opposite of "if" Example: unless (age >= 105)# if (age < 105) puts "young." else puts "old." end

35 until Similarly, "until" is the logical opposite of "while" Can specify a condition to have the loop stop (instead of continuing) Example i = 0 until (i >= 5) # while (i < 5), parenthesis not required puts I i = i + 1 end

36 Methods Structure def method_name( parameter1, parameter2, …) statements end Simple Example: def print_ryan puts "Ryan" end

37 Parameters No class/type required, just name them! Example: def cumulative_sum(num1, num2) sum = 0 for i in num1..num2 sum = sum + i end return sum end # call the method and print the result puts(cumulative_sum(1,5))

38 Return Ruby methods return the value of the last statement in the method, so… def add(num1, num2) sum = num1 + num2 return sum end can become def add(num1, num2) num1 + num2 end

39 Method with array as parameter def max(first, *rest) result= first for x in rest do if (x > result) then result= x end return result end

40 Modules – require one.rb file into another Modules: Grouping of methods, classes, constants that make sense together…a bit like a library

41 User Input "gets" method obtains input from a user Example name = gets puts "hello " + name + "!" Use chomp to get rid of the extra line puts "hello" + name.chomp + "!" chomp removes trailing new lines

42 Changing types You may want to treat a String a number or a number as a String to_i – converts to an integer (FixNum) to_f – converts a String to a Float to_s – converts a number to a String Examples "3.5".to_i  3 "3.5".to_f  3.5 3.to_s  "3"

43 Constants In Ruby, constants begin with an Uppercase They should be assigned a value at most once This is why local variables begin with a lowercase Example: Width = 5 def square puts ("*" * Width + "\n") * Width end

44 Handling Exceptions: Catch Throw def sample # a silly method that throws and exception x=1 throw :foo if x==1 end begin puts ‘start’ sample # call above method puts ‘end’ rescue puts ‘exception found’ end General format of handling exceptions begin # - code that could cause exception rescue OneTypeOfException # - code to run if OneTypeException rescue AnotherTypeOfException # - code to run if AnotherTypeOfException else # code to run for Other exceptions end

45 Classes

46 Slide 46 Simple Class class Point def initialize(x, y) @x = x @y = y end def x #defining class variable @x end def x=(value) @x = value end #code using class p = Point.new(3,4) puts "p.x is #{p.x}" p.x = 44

47 Another class - Book class Book def initialize(title, author, date) @title = title #various variables @author = author @date = date end def to_s#method to make string "Book: #@title by #{@author} on #{@date}" end

48 Book class—adding methods to access class variables (setter/getter) class Book def initialize(title, author, date) # constructor @title = title @author = author @date = date end def author #method to access class variable author @author end def author=(new_author) #method to set value of class variable author @author = new_author end

49 Class Inheritance (calling parent-super) class Book def initialize(title, author, date) @title = title @author = author @date = date end def to_s "Book: #@title by #{@author} on #{@date}" end class ElectronicBook < Book def initialize(title, author, date, format) super(title, author, date) @format = format end def to_s super + " in #{@format}" end

50 Protection Types –here for methos class Foo def method1 end def method2 end.... public :method1, method3 protected :method2 private :method4, method5 end Public Methods: Public methods can be called by anyone. Methods are public by default except for initialize, which is always private. Private Methods: Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members. Protected Methods: A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

51 Creating a method operator called < (w/test class showing using it) class Book attr_reader :title def initialize(title, author, date) @title = title @author = author @date = date end def <(book) return false if book.kind_of(Book) title < book.title end require 'test/unit' require 'book' class TestExample < Test::Unit::TestCase def test_operator cat = Book.new("Cat", "Me", "1990") dog = Book.new("Dog", "Me", "1990") assert( cat < dog) end

52 File I/O file = File.open('testFile') while line = file.gets puts line end file.close File.open('testFile') do |file| while line = file.gets puts line end File.open('testFile') do |file| file.each_line {|line| puts line} end IO.foreach('testFile') {|line| puts line} puts IO.readlines('testFile') array = IO.readlines('testFile') rread-only, start at beginning of file r+read/write, start at beginning of file wwrite-only, start at beginning of file w+read/write, start at beginning of file awrite-only, append to end of file a+read/write, start at end of file bBinary mode, Windows only, combine with above mode = 'a' File.open('testFile', mode) do |file| file.print 'cat' file.puts 'dog' file.puts 5 end File.open('testFile', mode) do |file| file << 'cat' << "dog\n" << 5 << "\n" end

53 Threads require 'net/http' pages = %w{ www.yahoo.com www.google.com slashdot.org} threads = [] for page_to_fetch in pages threads << Thread.new(page_to_fetch) do |url| browser = Net::HTTP.new(url, 80) puts "Fetching #{url}" response = browser.get('/', nil) puts "Got #{url}: #{response.message}" end threads.each {|thread| thread.join } Fetching www.yahoo.com Fetching www.google.com Fetching slashdot.org Got www.yahoo.com: OK Got www.google.com: OK Got slashdot.org: OK Note: Thread and HTTP are classes in ruby NOTE: General code to create thread & associate running code (do block) and join it to thread pool thread = Thread.new do #code to execute in Thread running end thread.join

54 References Web Sites http://www.ruby-lang.org/en/ http://rubyonrails.org/ Books Programming Ruby: The Pragmatic Programmers' Guide (http://www.rubycentral.com/book/)http://www.rubycentral.com/book/ Agile Web Development with Rails Rails Recipes Advanced Rails Recipes


Download ppt "Ruby. What is Ruby? Programming Language Object-oriented Interpreted Popular- Ruby on Rails a framework for Web Server Programming."

Similar presentations


Ads by Google