• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
ruby1_6up
 

ruby1_6up

on

  • 402 views

 

Statistics

Views

Total Views
402
Views on SlideShare
402
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    ruby1_6up ruby1_6up Document Transcript

    • Ruby A quick Ruby Tutorial • Invented by Yukihiro Matsumoto, “Matz” • 1995 • Fully object-oriented COMP313 Source: Programming Ruby, The Pragmatic • alternative to Perl or Python Programmers’ Guide by Dave Thomas, Chad Fowler, and Andy Hunt How to run Simple method example • Command line: ruby <file> def sum (n1, n2) n1 + n2 • Interactive: irb end • Resources: sum( 3 , 4) => 7 – see web page sum(“cat”, “dog”) => “catdog” – man ruby load “fact.rb” fact(10) => 3628800 executable shell script Method calls #!/usr/bin/ruby "gin joint".length 9 print “hello worldn” "Rick".index("c") 2 -1942.abs 1942 or better: #!/usr/bin/env ruby make file executable: chmod +x file.rb Strings: ‘asn’ => “asn” x=3 y = “x is #{x}” => “x is 3” 1
    • Another method definition Name conventions/rules def say_goodnight(name) • local var: start with lowercase or _ "Good night, #{name}" • global var: start with $ end • instance var: start with @ puts say_goodnight('Ma') • class var: start with @@ • class names, constant: start uppercase following: any letter/digit/_ multiwords produces: Good night, Ma either _ (instance) or mixed case (class), methods may end in ?,!,= Naming examples Arrays and Hashes • local: name, fish_and_chips, _26 • indexed collections, grow as needed • global: $debug, $_, $plan9 • array: index/key is 0-based integer • hash: index/key is any object • instance: @name, @point_1 a = [ 1, 2, “3”, “hello”] • class: @@total, @@SINGLE, a[0] => 1 a[2] => “3” • constant/class: PI, MyClass, a[5] => nil (ala null in Java, but proper Object) FeetPerMile a[6] = 1 a => [1, 2, “3”, “hello”, nil, nil, 1] Hash examples Control: if example inst = { “a” => 1, “b” => 2 } if count > 10 inst[“a”] => 1 puts "Try again" inst[“c”] => nil elsif tries == 3 inst = Hash.new(0) #explicit new with default 0 instead of nil for empty slots puts "You lose" inst[“a”] => 0 else inst[“a”] += 1 puts "Enter a number" inst[“a”] => 1 end 2
    • Control: while example nil is treated as false while weight < 100 and num_pallets <= 30 while line = gets pallet = next_pallet() puts line.downcase weight += pallet.weight end num_pallets += 1 end builtin support for Regular Statement modifiers expressions • useful for single statement if or while /Perl|Python/ matches Perl or Python • similar to Perl /ab*c/ matches one a, zero or more bs and one c • statement followed by condition: /ab+c/ matches one a, one or more bs and one c puts "Danger" if radiation > 3000 /s/ matches any white space /d/ matches any digit square = 2 /w/ characters in typical words square = square*square while square < 1000 /./ any character (more later) more on regexps Code blocks and yield if line =~ /Perl|Python/ def call_block puts "Scripting language mentioned: #{line}" puts "Start of method" end yield yield puts "End of method" line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' end line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby’ call_block { puts "In the block" } produces: # replace all occurances of both ‘Perl’ and ‘Python’ with ‘Ruby’ Start of method line.gsub(/Perl|Python/, 'Ruby') In the block In the block End of method 3
    • parameters for yield Code blocks for iteration def call_block animals = %w( ant bee cat dog elk ) # create an array yield("hello",2) # shortcut for animals = {“ant”,”bee”,”cat”,”dog”,”elk”} end animals.each {|animal| puts animal } # iterate produces: then ant bee cat call_block { | s, n | puts s*n, "n" } prints dog hellohello elk Implement “each” with “yield” More iterations # within class Array... [ 'cat', 'dog', 'horse' ].each {|name| print name, " "} def each 5.times { print "*" } for every element # <-- not valid Ruby 3.upto(6) {|i| print i } yield(element) ('a'..'e').each {|char| print char } end [1,2,3].find { |x| x > 1} end (1...10).find_all { |x| x < 3} I/O leaving the Perl legacy behind • puts and print, and C-like printf: while gets printf("Number: %5.2f,nString: %sn", 1.23, if /Ruby/ "hello") print #produces: end Number: 1.23, end String: hello #input ARGF.each {|line| print line if line =~ /Ruby/ } line = gets print line print ARGF.grep(/Ruby/) 4
    • Classes override to_s class Song s.to_s => "#<Song:0x2282d0>" def initialize(name, artist, duration) @name = name class Song @artist = artist def to_s @duration = duration "Song: #@name--#@artist (#@duration)" end end end end song = Song.new("Bicylops", "Fleck", 260) s.to_s => "Song: Bicylops--Fleck (260 )” Some subclass supply to_s for subclass class KaraokeSong < Song class KaraokeSong < Song # Format as a string by appending lyrics to parent's to_s value. def initialize(name, artist, duration, lyrics) def to_s super(name, artist, duration) super + " [#@lyrics]" @lyrics = lyrics end end end end song.to_s "Song: My Way--Sinatra (225) [And now, the...]" song = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") song.to_s "Song: My Way--Sinatra (225)" Accessors class Song def name @name end end s.name => “My Way” # simpler way to achieve the same class Song attr_reader :name, :artist, :duration end 5