general purpose language ruby kit chan comp3351 programming languages november 9, 2007
TRANSCRIPT
General Purpose Language General Purpose Language Ruby Ruby
Kit ChanKit Chan
COMP3351COMP3351
Programming LanguagesProgramming Languages
November 9, 2007November 9, 2007
OutlineOutlineReferenceReference IntroductionIntroductionRuby isRuby isFeaturesFeaturesArrayArrayLoopLoopRuby v.s. JavaRuby v.s. JavaDuck TypingDuck TypingDynamic TypingDynamic TypingType Tag CheckingType Tag CheckingFunctional ProgrammingFunctional Programming
ReferenceReferenceWikipediaWikipedia
http://en.wikipedia.org/wiki/Ruby_(programming_language)http://en.wikipedia.org/wiki/Ruby_(programming_language)
http://en.wikipedia.org/wiki/Comparison_of_programming_languageshttp://en.wikipedia.org/wiki/Comparison_of_programming_languages
Ruby Official WebsiteRuby Official Websitehttp://www.ruby-lang.org/enhttp://www.ruby-lang.org/en//
Learning RubyLearning Rubyhttp://www.math.umd.edu/~dcarrera/ruby/0.3/index.htmlhttp://www.math.umd.edu/~dcarrera/ruby/0.3/index.html
Duck TypingDuck Typinghttp://rubylearning.com/satishtalim/duck_typing.htmlhttp://rubylearning.com/satishtalim/duck_typing.html
IntroductionIntroductionDeveloped by Yukihiro “Matz” Matsumoto, in Developed by Yukihiro “Matz” Matsumoto, in
Feb, 1993Feb, 1993First released in 1995First released in 1995
1.8.6 Ruby 1.9 developed March, 20071.8.6 Ruby 1.9 developed March, 2007NamedNamed
As a gemstone because of a joke with in As a gemstone because of a joke with in Matsumoto’s friends alluding to Perl’s nameMatsumoto’s friends alluding to Perl’s name
Ruby isRuby isCross-platform Operating SystemCross-platform Operating SystemCombines syntax byCombines syntax by
PerlPerlSmalltalk-like OO featuresSmalltalk-like OO features
Shares features withShares features withLispLispPythonPythonDylanDylanCLUCLU
Ruby isRuby isThe interpreted scripting language for The interpreted scripting language for
QuickQuickEasy OO programmingEasy OO programming
designed for programmer productivitydesigned for programmer productivityStraight-forwardStraight-forward
principle of least surprise (POLS)principle of least surprise (POLS)Ruby behaves in a way that minimizing confusion for Ruby behaves in a way that minimizing confusion for
experienced usersexperienced users
After you learn Ruby very wellAfter you learn Ruby very well
Ruby isRuby isObedientObedient
>> 'Hello World' >> 'Hello World'
=> "Hello World”=> "Hello World”>> 'blink ' * 4 >> 'blink ' * 4 => "blink blink blink blink " => "blink blink blink blink "
Your CalculatorYour Calculator>> 1+1 >> 1+1
=> 2 => 2
OrOr
>> 2**2**2 >> 2**2**2
=> 16 => 16
FeaturesFeaturesObject-orientedObject-orientedFour levels of variables:Four levels of variables:
GlobalGlobal $var$var InstanceInstance @var@varLocalLocal [a-z] or _; var[a-z] or _; varConstantConstant [A-Z][A-Z]
Exception handlingException handling Iterators & closuresIterators & closuresAutomatic garbage collectingAutomatic garbage collectingHighly portableHighly portable
http://tryruby.hobix.com/http://tryruby.hobix.com/
ArrayArray >> numbers = ["zero", "one", "two", "three", "four"] >> numbers = ["zero", "one", "two", "three", "four"] => ["zero", "one", "two", "three", "four"] => ["zero", "one", "two", "three", "four"] => Array => Array >> numbers[0] >> numbers[0] => "zero" => "zero"
What arrays do?What arrays do? >> numbers[0].class >> numbers[0].class => String => String >> numbers[0].upcase >> numbers[0].upcase => "ZERO" => "ZERO" >> numbers[0].reverse >> numbers[0].reverse => "orez" => "orez"
LoopLoop If I knew Ruby when I was in grade school…….If I knew Ruby when I was in grade school…….
>> 100.times do >> 100.times do .. puts "I won't do that again" .. puts "I won't do that again" .. end .. end
I won't do that again I won't do that again
=> 100=> 100My life was going to be much easier My life was going to be much easier
Ruby v.s. Java- SyntaxRuby v.s. Java- Syntax begin_time = Time.now.to_ibegin_time = Time.now.to_i i = 0i = 0 100.times do100.times do i += 1i += 1 j = 0j = 0 10.times do10.times do j += 1j += 1 k = 0k = 0 100.times do100.times do k += 1k += 1 puts i.to_s + " + " + j.to_s + " + " + puts i.to_s + " + " + j.to_s + " + " +
k.to_sk.to_s endend endend endend end_time = Time.now.to_iend_time = Time.now.to_i difference = end_time - begin_timedifference = end_time - begin_time puts "It took " + difference.to_s + " seconds"puts "It took " + difference.to_s + " seconds" ho = getsho = gets
class test { public static void main(String[] args) { long startTime = System.currentTimeMillis(); for (int i=0; i<=100 ; i++ ) { for (int j=0; j<=10 ; j++) { for (int k=0; k<=100 ; k++ ) { System.out.println( i + " + " + j + " + " + k);}}} long endTime = System.currentTimeMillis(); long difference = (endTime - startTime)/1000; System.out.println("It took " + difference + "
seconds"); } }
Ruby v.s. JavaRuby v.s. Java Performance Performance
Ruby: 24 – 26 secondsRuby: 24 – 26 seconds Java: 1 – 2 secondsJava: 1 – 2 seconds
LanguageLanguage ParadigmParadigm Type Type
CheckingChecking
JavaJava ImperativeImperativeObject-orientedObject-orientedGenericGeneric
StaticStatic
RubyRuby ImperativeImperativeObject-orientedObject-orientedFunctionalFunctionalAspect-orientedAspect-oriented
DynamicDynamic
(duck)(duck)
Duck TypingDuck TypingRuby interpreter is happy to treat it as it were a Ruby interpreter is happy to treat it as it were a
duckduck If an object walks and talks like a duckIf an object walks and talks like a duck
Duck typing meansDuck typing meansAn object type is defined by what it can doAn object type is defined by what it can doNot by what it isNot by what it is
Duck typing refers toDuck typing refers to less concerned with the class of an object less concerned with the class of an object more concerned with what methods can be called more concerned with what methods can be called
on it on it what operations can be performedwhat operations can be performed
Duck TypingDuck Typingwe use respond_to? we use respond_to?
ExampleExample >> puts ('A string'.respond_to? :to_str) >> puts ('A string'.respond_to? :to_str) true true => nil => nil >> puts (Exception.new.respond_to? :to_str) >> puts (Exception.new.respond_to? :to_str) true true => nil => nil
If an object quacks like a duck, just treat it as a If an object quacks like a duck, just treat it as a duck….duck….
We should treat objects to the methods they defineWe should treat objects to the methods they define
Duck TypingDuck Typing >> class Duck >> class Duck
.. def quack .. def quack
.. 'Quack!' .. 'Quack!'
.. end .. end
.. def swim .. def swim
.. 'Paddle paddle paddle...' .. 'Paddle paddle paddle...'
.. end .. end
.. end .. end
=> nil => nil
>> class Goose >> class Goose
.. def honk .. def honk
.. 'Honk!' .. 'Honk!'
.. end .. end
.. def swim .. def swim
.. 'Splash splash splash...' .. 'Splash splash splash...'
.. end .. end
.. end .. end
=> nil => nil
>>>>
Duck TypingDuck Typing >> class DuckRecording >> class DuckRecording
.. def quack .. def quack
.. play .. play
.. end .. end
.. def play .. def play
.. 'Quack' .. 'Quack'
.. end .. end
.. end .. end
=> nil => nil
>> def make_it_quack(duck) .. duck.quack .. end => nil >> puts make_it_quack(Duck.new) Quack! >> puts make_it_quack(DuckRecording.new) Quack => nil >> def make_it_swim(duck) .. duck.swim .. end => nil >> puts make_it_swim(Duck.new) Paddle paddle paddle... => nil >> puts make_it_swim(Goose.new) Splash splash splash... => nil
Add Method to Class InstancesAdd Method to Class Instances Add methods to individual class instancesAdd methods to individual class instances
class Duck class Duck def quack def quack puts 'Quack!' puts 'Quack!'
end end def swim def swim puts 'Paddle paddle paddle...' puts 'Paddle paddle paddle...'
end end endend d = Duck.new #create new instance of the classd = Duck.new #create new instance of the class d.quackd.quack #call method#call method d.swimd.swim #call method#call method def d.walkdef d.walk #override existing method with#override existing method with
#new functionality#new functionality puts 'I am walking ... walking'puts 'I am walking ... walking' endend
d.walkd.walk => nil=> nil => #<Duck:0x6cc7ddc>=> #<Duck:0x6cc7ddc> Quack!Quack! => nil=> nil Paddle paddle paddle...Paddle paddle paddle... => nil=> nil => nil=> nil I am walking ... walkingI am walking ... walking => nil=> nil irb(main):022:0> irb(main):022:0>
Dynamic TypingDynamic TypingRuby, the data types are not wholly declared on Ruby, the data types are not wholly declared on
variablevariable
Data associated with variables are not known Data associated with variables are not known until the time of executionuntil the time of execution
Advantage:Advantage: flexibilityflexibilityLess work for the programmerLess work for the programmer
Type Tag CheckingType Tag CheckingRuby is dynamically typedRuby is dynamically typed
it supports run-time dispatch on tagged datait supports run-time dispatch on tagged data
Takes place at run-timeTakes place at run-timevalues bound in variables can acquire different tags values bound in variables can acquire different tags
depending on the execution pathdepending on the execution path
ExampleExamplevar x var x #declares the name x#declares the name xx :=1x :=1 #associates int val 1 to name x#associates int val 1 to name xx :=“hi”x :=“hi” #associates the string val “hi” to name x#associates the string val “hi” to name x
…………………………illegal illegal binding x to values of inconsistent typebinding x to values of inconsistent type
Pure Dynamically typed system allows the Pure Dynamically typed system allows the executionexecutionType tags are attached to valuesType tags are attached to values
Dynamic typing catches errors during program Dynamic typing catches errors during program executionexecution
Example......contExample......contDynamic typing keeps all program values Dynamic typing keeps all program values
“tagged” “tagged”
Checks the tag before using any value in an Checks the tag before using any value in an operationoperationvar x :=1 var x :=1 #binds val 1 to x#binds val 1 to xvar y := “hi”var y := “hi” #binds val “hi” to y#binds val “hi” to yvar z := x + yvar z := x + y #add x to y#add x to y
Example......contExample......contThe value bound to x be a pair (integer, 1)The value bound to x be a pair (integer, 1)
The value bound to y be a pair (string, “hi”)The value bound to y be a pair (string, “hi”)
Attempts to execute the 3Attempts to execute the 3rdrd line, line,Checks the type tags integer and stringChecks the type tags integer and string If the operation + (addition) is not definedIf the operation + (addition) is not defined
An error is signaledAn error is signaled
Why Ruby?Why Ruby?High productivity for programmersHigh productivity for programmers
Execution time is not the main concernExecution time is not the main concernWeb DevelopmentsWeb Developments
Projects like Ruby on RailsProjects like Ruby on RailsFunctional ProgrammingFunctional Programming
Paradigm treats computation as the evaluation of Paradigm treats computation as the evaluation of mathematical functionsmathematical functionsEmphasize on application of functionsEmphasize on application of functions
Largely being used in academiaLargely being used in academiaLambda calculusLambda calculus
Forms the foundation for most models of functional programmingForms the foundation for most models of functional programming
Thank you !!Thank you !!