1 / 60

Chapter 14

Chapter 14. Ruby. Ruby download at rubyforge. Ruby , rubygems and rails are all separately available from rubyforge. In the next text chapter, ruby on rails is used. There is a single distribution which contains ruby, mysql, apache, php and rails. It is also at rubyforge:

galvin
Download Presentation

Chapter 14

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 14 Ruby

  2. Ruby download at rubyforge • Ruby, rubygems and rails are all separately available from rubyforge. • In the next text chapter, ruby on rails is used. There is a single distribution which contains ruby, mysql, apache, php and rails. It is also at rubyforge: http://instantrails.rubyforge.org/wiki/wiki.pl • But using ruby from instantrails apache or mongrel is not exactly the same since it has its own command window which must be used – you can’t use a DOS window. • You can navigate to ruby within the instantrails distribution and do examples in a command window there. • If you only have xampp – you’ll have to install instant rails

  3. The html doc that comes with the install is an entire ruby text

  4. On my p: drive the ruby doc is not available

  5. Create cmd.exe shortcut to ruby\bin & run from commandline c:\ruby\bin>ruby puts "hello Siobhan" ^D hello Siobhan c:\ruby\bin> puts and print both display string output

  6. Running a few text examples in irb: the commandline interpreter

  7. chomp and simple input using gets

  8. Examples of numbers 123456                    # Fixnum 123_456             # Fixnum (underscore ignored) -543                      # Negative Fixnum 123_456_789_123_345_789   # Bignum 0xaabb                    # Hexadecimal 0377                      # Octal -0b101_010                # Binary (negated)

  9. Number types C:\ruby\bin>ruby numbers.rb Fixnum 8 Fixnum 64 Fixnum 4096 Fixnum 16777216 Bignum 281474976710656 Bignum 79228162514264337593543950336 Bignum 6277101735386680763835789423207666416102355444464034512896

  10. Numbers.rb #ruby program num = 8 7.times do print num.class, " ", num, "\n“ #num.type is deprecated num *= num end

  11. Additional examples from Programming Ruby def saynight(name) result="nightnight, "+name return result end puts saynight("Shanny") C:\ruby\bin>ruby saynight.rb nightnight, Shanny def saynight(name) result="nightnight, #{name}" end puts saynight("Shanny") C:\ruby\bin>ruby saynight2.rb nightnight, Shanny

  12. Quadratic polynomial eval from text #quad eval #input 3 float coeffs and the x point puts "input a " a=gets.to_f puts "input b " b=gets.to_f puts "input c " c=gets.to_f puts "input x " x=gets.to_f ans=a*x*x+b*x+c puts "that quadratic evaluates to #{ans}"

  13. Running quadeval C:\ruby\bin>ruby quadeval.rb input a 5 input b 2 input c -1 input x 4 that quadratic evaluates to 87.0 C:\ruby\bin>

  14. case year=gets kind = case year when 1850..1889 then "Blues" when 1890..1909 then "Ragtime" when 1910..1929 then "New Orleans Jazz" when 1930..1939 then "Swing" when 1940..1950 then "Bebop" else "Jazz" end puts kind

  15. Run caseex2.rb C:\ruby\bin>ruby caseex2.rb 1934 Jazz

  16. Notes from pragmatic programmers:yield- because of return 2nd yield not executed def greet(name) yield return "Hello, #{name}" yield end puts greet("Shanny") {puts "hi"} C:\ruby\bin>ruby yieldex1.rb hi Hello, Shanny

  17. More notes from pragmatic programmers:Iterator example #iterater animals =%w(ant mouse giraffe lion dog elk) animals.each{|animal| puts animal} C:\ruby\bin>ruby it1.rb ant mouse giraffe lion dog elk

  18. Iterator example 2: methods in ruby #a few lines of code illustrating method calls on objects ['cat','dog','horse'].each{|name| print name," "} 5.times{ print "*"} 3.upto(6){|i| print i} ('a'..'e').each{|char| print char} C:\ruby\bin>ruby it2.rb cat dog horse *****3456abcde

  19. process_names.rb: an array example from the text # process_names.rb - A simple Ruby program to # illustrate the use of arrays # Input: A list of lines of text, where each line # is a person's name # Output: The input names, after all letters are # converted to uppercase, in alphabetical order index = 0 names = Array.new # Loop to read the names and process them while(name = gets) # Convert the name's letters to uppercase and put it # in the names array names[index] = name.chomp.upcase index += 1 end # Sort the array in place and display it names.sort! puts "The sorted array" for name in names puts name end

  20. process_names.. use ctrl-z to end input C:\ruby>ruby process_names.rb aaa fffff cccccccc bbbbbbb rrrrr ttt uuu pppppppp qq mmmmmm zzzzz ^Z The sorted array AAA BBBBBBB CCCCCCCC FFFFF MMMMMM PPPPPPPP QQ RRRRR TTT UUU ZZZZZ C:\ruby>

  21. A hash example x={"a"=>1, "b"=>2,"hello"=>56} z=x.keys y=x.values z.each{|a|puts a} y.each{|a|puts a} if x.has_key?("hello")then puts "yes" end

  22. More hash: remember coins? h={'penny'=>1,'nickel'=>5,'dime'=>10,'quarter'=>25} puts "hash" h.each{|i| puts i}#goes through keys and values... no particular order a=[1,5,10,25] a.each{|i| puts i} puts "coins sm to lg" a.reverse! #we need to go through hash in large to small order puts "coins lg to small" a.each{|i| puts i} change=gets.to_i #get an int from input puts "change to make=#{change}" i=0 while(change>0) q=change/a[i] change=change %a[i] puts “size is #{a[i]} and how many? #{q}“ #how many of each denomination needed i+=1 end

  23. Run of prev example hash quarter 25 nickel 5 penny 1 dime 10 1 5 10 25 coins sm to lg coins lg to small 25 10 5 1 347 change to make=347 size is 25 and how many? 13 size is 10 and how many? 2 size is 5 and how many? 0 size is 1 and how many? 2

  24. Text’s word table example modified so it uses a file freq = Hash.new line_words = Array.new arr=Array.new # Main loop to get and process lines of text from file arr = IO.readlines("file.txt") file_words="" #get all the words into a single long string for sentence in arr file_words=file_words+ " " + sentence end # Split the line into words file_words = file_words.chomp.split( /[ \.,;:!\?]\s*/) # Loop to count the words (either increment or initialize to 1) for word in file_words if freq.has_key?(word) then freq[word] = freq[word] + 1 else freq[word] = 1 end end #end # Display the words and their frequencies puts "\n Word \t\t Frequency \n\n" for word in freq.keys.sort puts " #{word} \t\t #{freq[word]}" end

  25. Word frequency in a text file C:\ruby>ruby words_from_file.rb Word Frequency 1 a 8 a 1 and 1 be 1 by 1 file 1 from 2 is 1 modified 1 of 1 processed 1 program 1 short 1 short 1 slightly 1 taken 1 text 1 the 3 then 1 this 1 to 1 words 1 C:\ruby>

  26. Class example # Stack2_class.rb - a class to implement a stack-like # structure in an array class Stack2_class # Constructor - parameter is the size of the stack - default is 100 def initialize(len = 100) @stack_ref = Array.new(len) @max_len = len @top_index = -1 end # push method def push(number) if @top_index == @max_len puts "Error in push - stack is full" else @top_index += 1 @stack_ref[@top_index] = number end end # pop method def pop() if @top_index == -1 puts "Error in pop - stack is empty" else @top_index -= 1 end end

  27. Stack continued # top method def top() if @top_index > -1 return @stack_ref[@top_index] else puts "Error in top - no elements" end end # top2 method def top2 if @top_index > 0 return @stack_ref[@top_index - 1] else puts "Error in top2 - there are not 2 elements" end end # empty method def empty() @topIndex == -1 end end

  28. Using the stack: note use of require to import or include a file require "Stack_class" #test Stack2_class mystack = Stack2_class.new(50) mystack.push(50) mystack.push(40) puts "top elt is: #{mystack.top}" mystack.pop puts "after pop new top elt is: #{mystack.top}" mystack.pop mystack.pop #last pop generates empty stack error

  29. Running stack2test.rb C:\ruby\bin>ruby stack2test.rb top elt is: 40 after pop new top elt is: 50 Error in pop - stack is empty C:\ruby\bin>

  30. Postfix evaluation • Many problems can be handled with a stack for evaluation purposes. Postfix notation is an example. • In infix, a binary operator appears between its operands. In postfix, the operator appears after its operands. • A stack is used to store operands. When an operator is encountered, two operands are popped, the operator is applied and the result is pushed. • If the expression is legal, one value remains on the stack at the end.

  31. The program – putting control together with array processing #part1 get the input as an array of ints and ops require "Stack_class" #test Stack2_class mystack = Stack2_class.new(50) expression = Array.new puts "enter postfix\n" # get a line of input text line = gets # Split the line into words expression = line.chomp.split( /[ \.,;:!\?]\s*/)

  32. 2nd part… process array contents # Loop to process postfix expression for word in expression #puts word +"\n" if word[0,1] >= '0' and word[0,1]<='9' mystack.push(word.to_i) else a=mystack.top mystack.pop b=mystack.top mystack.pop case word[0,1] when '+' then mystack.push(a+b) when '-' then mystack.push(b-a) when '*' then mystack.push(a*b) when '/' then mystack.push(b/a) when '%' then mystack.push(b%a) end #case end #if end #for all words puts mystack.top

  33. Postfix evaluation Processing postfix for (10*10*10 / 50 +10)/3 C:\ruby\bin>ruby postfix.rb enter postfix 10 10 10 * * 50 / 10 + 3 / 10 And for input errors: C:\ruby\bin>ruby postfix.rb enter postfix 10 10 10 * / 50 + / 3 10 - Error in top - no elements Error in pop - stack is empty postfix.rb:32: undefined method `/' for nil:NilClass (NoMethodError) from postfix.rb:14:in `each' from postfix.rb:14

  34. remarks • I used this postfix application later, too, as an example in the next chapter, Ruby on Rails.

  35. A song class class Song @@plays=0 #glbal def play @plays +=1 #field or instance variable @@plays +=1 #static variable puts "plays #@@plays" end def to_s "Song: #@name--#@artist (#@duration) " end def initialize(name,artist,duration) @plays=0 @name=name @artist=artist @duration=duration end attr_reader :name, :artist, :duration attr_writer :name, :artist, :duration end

  36. Karaoke class – note “include” require "song.rb“####include file class KaraokeSong < Song def to_s #to string method super + "{#@lyrics}" end def initialize(name,artist,duration,lyrics) #constructor super(name,artist,duration) @lyrics=lyrics end end ks=KaraokeSong.new("Somewhere","James Darin", 166,"beyong the sea") #call constructor ks2=KaraokeSong.new("Over there","Andrews Sisters", 122,"over there...") ks.play ks2.play puts ks.inspect #a predefined method puts ks.to_s puts ks.name ks.name="Someday Soon" ks.artist="Ian Tyson" ks.duration=201 puts ks.to_s

  37. Executing karaoke C:\ruby\bin>ruby karaoke.rb plays 1 plays 2 #<KaraokeSong:0x2b29600 @artist="James Darin", @plays=1, @lyrics="beyong the sea ", @duration=166, @name="Somewhere"> Song: Somewhere--James Darin (166) {beyong the sea} Somewhere Song: Someday Soon--Ian Tyson (201) {beyong the sea}

  38. You’ll want to edit index.html…notice apache is running on port 80

  39. CGI-Bin from apache

  40. The ruby program #!C:\InstantRails\ruby\bin\ruby.exe print "Content-type:text/html\r\n\r\n" print"<html><body>Hello out there from Ruby CGI...it is #{Time.now}</Body></html>\r\n"

  41. In httpd conf file # I added pl and rb below AddHandler cgi-script .cgi .pl .rb

  42. Create a form using cgi #!C:\ruby\bin\ruby.exe require "cgi" cgi = CGI.new("html3") # add HTML generation methods cgi.out{ cgi.html{ cgi.head{ "\n"+cgi.title{"This Is a Test"} } + cgi.body{ "\n"+ cgi.form{"\n"+ cgi.hr + cgi.h1 { "A Form: " } + "\n"+ cgi.textarea("get_text") +"\n"+ cgi.br + cgi.submit } } } }

  43. The form

  44. A form <html> <FORM action="http://localhost/cgi-bin/rubyform.rb" method="get"> <P> <LABEL for="firstname">First name: </LABEL> <INPUT type="text" name="firstname"><BR> <LABEL for="lastname">Last name: </LABEL> <INPUT type="text" name="lastname"><BR> <LABEL for="email">email: </LABEL> <INPUT type="text" name="email"><BR> <INPUT type="radio" name="sex" value="Male"> Male<BR> <INPUT type="radio" name="sex" value="Female"> Female<BR> <INPUT type="submit" value="Send"> <INPUT type="reset"> </P> </FORM> </html>

  45. And handling parameters in cgi #!C:\ruby\bin\ruby.exe require "cgi" cgi = CGI.new("html3") # add HTML generation methods cgi.out{ cgi.html{ cgi.body{ "firstname #{cgi['firstname']} " +cgi.br+ "lastname #{cgi['lastname']} " +cgi.br+ "email#{cgi['email']} " } } } Note… you could also define a var parms=cgi.params And then access parm[‘pname’]

  46. Form and cgi at url:http://localhost/cgi-bin/rubyform.rb?firstname=aaa&lastname=dddd&email=xxxx

  47. And…doing arithmetic

  48. Binary numbers require "fillArray" require "dumpArray" require "addArray" x=fill() y=fill() z=add(x,y) dump(x) puts "+\n" dump(y) puts "=\n" dump(z)

  49. Add two arrays (as bin numbers) def add(a=[],b=[]) carry=0 z=Array.new() puts "length of input array is #{a.length}\n" for i in 0...a.length sum=a[i]+b[i]+carry carry=sum/2 z[i]=sum%2 # puts " i is #{i} carry is #{carry} sum is #{sum} z[i] is #{z[i]}" end return z end

  50. Fill from input def fill y=Array.new() puts "enter binary\n" line=gets.chomp #puts line pos=line.length-1 for i in 0...line.length y[pos]=line[i]-48 # puts y[pos] pos=pos-1 end for j in line.length...50 y[j]=0 end return y end

More Related