CS3157: Advanced Programming Lecture # ?? Ruby Shlomo Hershkop - - PowerPoint PPT Presentation

cs3157 advanced programming
SMART_READER_LITE
LIVE PREVIEW

CS3157: Advanced Programming Lecture # ?? Ruby Shlomo Hershkop - - PowerPoint PPT Presentation

CS3157: Advanced Programming Lecture # ?? Ruby Shlomo Hershkop shlomo@cs.columbia.edu 1 Announcement Please make sure to start HW3 If you are behind, contact me about lateness 2 Outline Ruby today Very brief overview of


slide-1
SLIDE 1

1

CS3157: Advanced Programming

Lecture # ?? Ruby

Shlomo Hershkop shlomo@cs.columbia.edu

slide-2
SLIDE 2

2

Announcement

Please make sure to start HW3

If you are behind, contact me about lateness

slide-3
SLIDE 3

3

Outline

Ruby today

Very brief overview of language Some parts will be faster than others Will work though examples in groups Please ask if you have a question

slide-4
SLIDE 4

4

Background

You saw how useful perl was (compared to

c/ c+ + )

You saw how many different ways there

was to do everything

There is a reason real geeks like perl

slide-5
SLIDE 5

5

There is also a reason this compiles

@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{ @p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;( $q*=2)+=$f=!fork;map{$P=$P[$f^ord ($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{ $_}=~/^[P.]/&& close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print

slide-6
SLIDE 6

6

Released in Dec 1994 Everything is an object Similar to perl in the fact its interpreted

slide-7
SLIDE 7

7

Interpreter

ri

Ruby information (perldoc equivalent) ri String Ri String# chop

start ruby interpreter

irb

Interactive ruby interpreter – good for testing small

programs

slide-8
SLIDE 8

8

basics

Language basics

Number handling Variables conditions

slide-9
SLIDE 9

9

basics

Can get it to evaluate expressions

2 + 4

ints

3 / 2

ints

3.0 / 2

floats

* * and %

slide-10
SLIDE 10

10

Strings

Anything between quotes Lots of built in functions

empty length reverse chop uppercase downcase swapcase * n

slide-11
SLIDE 11

11

variables

Begin with lowercase Declared and assigned in same step Constant variables begin with upper case

Will just warn on changes (will still work)

Global variables begin with $

slide-12
SLIDE 12

12

Comments begin with # Multi lines can be escaped

Use the slash to code across lines Easier to read sometimes

slide-13
SLIDE 13

13

Basic functions

puts

Put a string to terminal Return value is nil val = puts “Hello world!”

to_s and to_i

Convert to and from String and Integer/ Float

  • bjects

Important since to create long strings won’t

automatically happen like Java does it

slide-14
SLIDE 14

14

loops

yourINt.times do

Some code

end Simply loops through yourInt times

slide-15
SLIDE 15

15

groups

What is the sum of all the integers from

10 to 100?

slide-16
SLIDE 16

16

One idea

count = 10

sum = 0 91.times do sum + = count count + = 1 end puts “Sum is now “ + sum.to_s

slide-17
SLIDE 17

17

Question ?

So how would you count backwards ??

slide-18
SLIDE 18

18

User input

variable = gets

Will grab user input

Will append the newline variable.chomp

Will give you what you want ☺

variable = variable.chomp

slide-19
SLIDE 19

19

quotes

Single quotes are string literals Can use \ q and use your own delims \ q! someth’ing !

Or

‘someth\ ’ing’ Refer to variable inside quotes using # { ..} “this is the # { sum} ”

slide-20
SLIDE 20

20

  • ther

if condition

Something

end Combine with elsif while condition

stuff

end

slide-21
SLIDE 21

21

Basic…

Ok enough with basics Lets start with more sophisticated Data

structures

Will use it to build a program

slide-22
SLIDE 22

22

Arrays

Collection of objects numbers = [ "zero", "one", "two", "three",

"four" ]

numbers[ 3] .reverse collect = [ ]

collect = Array.new

collect[ 20] = “surf”

slide-23
SLIDE 23

23

Array functions

a = % w{ ant bee cat dog elk } arrays.sort arrays.reverse arrays.length Can also combine arrays using + and *

slide-24
SLIDE 24

24

Question

addresses = [ [ 285, "Ontario Dr"] , [ 17,

"Quebec St"] , [ 39, "Main St" ] ]

What will addresses.sort do ??

slide-25
SLIDE 25

25

Control sort

addresses.sort do | a,b|

  • a[ 1] < = > b[ 1]

end

slide-26
SLIDE 26

26

Can iterate through array quite easily addresses.each do | item|

puts “this is the “ + item

end

slide-27
SLIDE 27

27

How would you iterate through an array

with for loop ??

slide-28
SLIDE 28

28

addresses.length.times do | i|

puts "I have: " + addresses[ i]

end

slide-29
SLIDE 29

29

hashes

Hmmm look familiar

instSection = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', 'oboe' => 'woodwind', 'trumpet' => 'brass', 'violin' => 'string' } instSection[“cello”]

slide-30
SLIDE 30

30

Iterate through hash

somehash.each do | key, value|

  • puts key + " = > " + value

end somehash.each_key do | key|

  • puts key

end

slide-31
SLIDE 31

31

Reg Expression

if line =~ /Perl|Python/ puts "Scripting language mentioned: #{line}" end line.sub(/Perl/, 'Ruby') line.gsub(/Python/, 'Ruby')

slide-32
SLIDE 32

32

functions

Beyond basic usage, now lets talk about

how to program functions def say_hi puts "Hey, How are you?" end

slide-33
SLIDE 33

33

Pass args

def say_hi(name) puts "Hello " + name + ", How are you?" end

slide-34
SLIDE 34

34

Classes

As mentioned ruby is pure object oriented

language

So need to define classes if you want your own

  • bjects

Start with upper case letter Initialize function always called first Instance variables in class start with @

slide-35
SLIDE 35

35

class Address def initialize(street) @street = street end end

test = Address.new(“120 st”) test.inspect

slide-36
SLIDE 36

36

Another class

class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end end

slide-37
SLIDE 37

37

Always open

Can always add a new function to a class

by saying: class Song def to_s "Song: #{@name}--#{@artist} (#{@duration})" end end

slide-38
SLIDE 38

38

Inheritance

class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end end

slide-39
SLIDE 39

39

question

So what will happen when you call

KaraokeSong to_s ??

slide-40
SLIDE 40

40

functions

Would be useful to be able to ask the song class for

individual items class Song def name @name end def artist @artist end def duration @duration end end

slide-41
SLIDE 41

41

shortcut

class Song attr_reader :name, :artist, :duration End class Song attr_writer :duration end

slide-42
SLIDE 42

42

Calls wide stuff

  • @@
  • Needs to be initialized
  • Can also have class specific functions

class Example def instMeth # instance method end def Example.classMeth # class method end end

slide-43
SLIDE 43

43

Levels of privacy

Can control how much access you want to

share for each part of the class

Public

No privacy

Private

Complete private, no one except own class

Protected

Own class and subclasses

slide-44
SLIDE 44

44

class MyClass def method1 # default is 'public' #... end protected # subsequent methods will be 'protected' def method2 # will be 'protected' #... end private # subsequent methods will be 'private' def method3 # will be 'private' #... end public # subsequent methods will be 'public' def method4 # and this will be 'public' #... end end

slide-45
SLIDE 45

45

Method II

class MyClass def method1 end # ... and so on public :method1, :method4 protected :method2 private :method3 end

slide-46
SLIDE 46

46

What is this ?

class SongList def [](key) if key.kind_of?(Integer) return @songs[key] else for i in 0...@songs.length return @songs[i] if key == @songs[i].name end end return nil end end

slide-47
SLIDE 47

47

yield allows a block of code to run inside a

function

Can pass it args

slide-48
SLIDE 48

48

def fibUpTo(max) i1, i2 = 1, 1 # parallel assignment while i1 <= max yield i1 i1, i2 = i2, i1+i2 end end fibUpTo(1000) { |f| print f, " " }

slide-49
SLIDE 49

49

So Iterators unlike c+ + and Java are part

  • f the class not independent

Natural extension of object manipulation

slide-50
SLIDE 50

50

f = File.open("testfile") f.each do |line| print line end f.close

slide-51
SLIDE 51

51

closure

Proc object contains all current environment

snapshot of running state for use later def nTimes(aThing) return proc { |n| aThing * n } end p1 = nTimes(23) p1.call(3) » 69 p1.call(4) » 92 p2 = nTimes("Hello ") p2.call(3) » "Hello Hello Hello "

slide-52
SLIDE 52

52

Ranges

1..10 'a'..'z' 0...anArray.length Allows you to specify range of values Internal data structure with start and end

values

slide-53
SLIDE 53

53

(1..10).to_a digits = 0..9 digits.include?(5) » true digits.min » digits.max » 9 digits.reject {|i| i < 5 } » [5, 6, 7, 8, 9] digits.each do |digit| dial(digit) end

slide-54
SLIDE 54

54

More ranges

while gets print if /start/../end/ end

slide-55
SLIDE 55

55

Exception Handling

  • pFile = File.open(opName, "w")

begin # Exceptions raised by this code will # be caught by the following rescue clause while data = socket.read(512)

  • pFile.write(data)

end rescue SystemCallError $stderr.print "IO failed: " + $!

  • pFile.close

File.delete(opName) raise end

slide-56
SLIDE 56

56

More info

http: / / dev.rubycentral.com/ ref/

slide-57
SLIDE 57

57

next

Read up more on ruby on the web Install ruby-rails on your local machine Will meet on Wednesday and cover rails End of week, you should be creating cool

web based stuff (if server runs ruby ☺ )