Introduction to RubyNicola Calcavecchia - 19/04/2013calcavecchia@{elet.polimi.it|gmail.com}Principles of Programming Langu...
Main Features• Dynamically Typed.• Purely Object Oriented.• Supports Meta-Programming.• Garbage collected.• Supports inher...
History• Created byYukihiro Matsumoto (Matz) in 1995.• Influenced by Smalltalk, Perl, Lisp and Python• Current stable relea...
Diffusion• Killer apps:• Ruby on Rails (web framework)• Puppet, Chef (configuration management)• Capistrano (deploy managem...
Getting started• irb executable: interactive shell (i.e., REPL).• ruby executable: language interpreter.• File extensions:...
Hello World(and a glimpse at Ruby Syntax)print("Hello World");print("Hello World")• Semicolons are optional:• Practically ...
Data Types• Ruby has many built-in data types:• Numeric: Integer, Floats, Complex, Rational, etc.• String: single-quoted, ...
Data Types• Ruby has many built-in data types:• Numeric: Integer, Floats, Complex, Rational, etc.• String: single-quoted, ...
Numeric Types• Implemented as objects•All inherits from Numeric class404 # Fixnum1_000_000_000 # Better readability241.1 #...
Strings• Enclosed in single or double quotes• Small differences between the two• String interpolation• Unicode escapes• Mu...
Arrays• Dynamically sized• Untyped and mutable• Example:[1, 2, 3] # an array with three Fixnum objects[] #empty array[0] *...
Hashes• Unordered collection of key-value pairs• Mutable• Indexed by keysa = {} # create an empty hasha[one] = 1 # map str...
Symbols• Same as scheme symbols• Constant, immutable strings• I.e., placeholder for identifiers and strings• Always prefixed...
Boolean and Nil• true: logical true value• Singleton instance of TrueClass• false: logical false value• Singleton instance...
Rules for objects1. All variables are references to objects (there are noprimitive types!)2. Objects communicate via messa...
Object References• It always works with references to object (i.e., similarto Scheme, Java)• Call by object sharing:• When...
Classes and methods• class keyword to define a class• def to define methodsclass ClassName" def method1(par1, par2)" " expre...
Constructor and instancevariables• Method initialize is the constructor• Instance variables start with @ symbolclass Point...
Cleaner version...• Ruby supports “parallel assignments”• Return is implicit (i.e., like Scheme):• Last expression is retu...
Creating an object• Invoke constructor with newp = Point.new(10,20)• Invoking a method:print p.to_s• Sends the to_s messag...
Getters and Setters• Lets define getters and setters for Point classclass Point" def initialize(x,y)" " @x, @y = x, y" end"...
Getters and Setters• Concise way to define getters and setters• Use symbols to identify the instance variableclass Point"" ...
Defining new operatorsclass Point" attr_accessor :x, :y" def initialize(x,y)" " @x, @y = x, y" end" def +(other)" " Point.n...
ClassVariables andClass methods• Class variables are shared among allinstances of that class• Introduced with @@ prefix• Cl...
Inheritance• By default a class extends the Object class• Inherits all predefined methods• Classic subclass/superclass rela...
Modules• A container of:• Methods• Constants• Class variables• Modules cannot be instantiated• Effective way to create nam...
Nesting namespaces• Modules and classes can benested• Better readability and avoidname clashesmodule Base64" DIGITS = (A.....
Mixins• If module define some instance methods, they canbe “mixed-in” a class.• Mixin code can interact with code in the cl...
Control structures• Classic control structures:• If, else, elsif, case, etc. (terminated with “end” keyword)• Plus some sy...
Loops• Classic for, while, until, etc:• The object must have an each methodx = 0puts x += 1 while x < 10x = 0puts x += 1 u...
Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent...
Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent...
Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent...
Yield examplesdef my_method" yieldendmy_method{ puts "hello!"}Yield without parameters31
Yield examplesdef my_method" yieldendmy_method{ puts "hello!"}# This method expects a block.# It generates n values# of th...
Blocks• Delimited with curly braces or do end keywords (i.e., multi line).• If method does not “yield”, the block is ignor...
Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:...
Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:...
Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:...
Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:...
Converting blocks to procs• Blocks do not have a name• Blocks can be converted into proc• Use & (i.e., ampersand)# Explici...
Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluation35
Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluationdef test" puts "entering...
Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluationdef test" puts "entering...
References36
Upcoming SlideShare
Loading in …5
×

Introduction to Ruby Programming Language

1,041 views

Published on

Main concepts: objects, classes, modules, inheritance, blocks, procs, lambdas

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,041
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
59
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Introduction to Ruby Programming Language

  1. 1. Introduction to RubyNicola Calcavecchia - 19/04/2013calcavecchia@{elet.polimi.it|gmail.com}Principles of Programming Languages1
  2. 2. Main Features• Dynamically Typed.• Purely Object Oriented.• Supports Meta-Programming.• Garbage collected.• Supports inheritance and mixins.www.ruby-lang.org2
  3. 3. History• Created byYukihiro Matsumoto (Matz) in 1995.• Influenced by Smalltalk, Perl, Lisp and Python• Current stable release: 2.0.0-p0• Interpreters:• MRI (Matz’s Ruby Interpreter)• YARV (now official)• Others: JRuby, Rubinius, IronRuby3
  4. 4. Diffusion• Killer apps:• Ruby on Rails (web framework)• Puppet, Chef (configuration management)• Capistrano (deploy management utility)• and many others...Source: https://github.com/languages (5/04/2013)4
  5. 5. Getting started• irb executable: interactive shell (i.e., REPL).• ruby executable: language interpreter.• File extensions: .rbruby hello.rb5
  6. 6. Hello World(and a glimpse at Ruby Syntax)print("Hello World");print("Hello World")• Semicolons are optional:• Practically never used.• Use newline instead.• Classic (and verbose)• Parenthesis in methods are optional:• Cleaner syntax!• Works well for DSLs (will see later...).print "Hello World"Cool, but pay attention:f(3+2) + 1f (3+2) + 16
  7. 7. Data Types• Ruby has many built-in data types:• Numeric: Integer, Floats, Complex, Rational, etc.• String: single-quoted, doubly-quoted, here documents,backtick, characters, etc.• Array• Hash• Boolean and nil• etc.7
  8. 8. Data Types• Ruby has many built-in data types:• Numeric: Integer, Floats, Complex, Rational, etc.• String: single-quoted, doubly-quoted, here documents,backtick, characters, etc.• Array• Hash• Boolean and nil• etc.All are implementedby objects!7
  9. 9. Numeric Types• Implemented as objects•All inherits from Numeric class404 # Fixnum1_000_000_000 # Better readability241.1 # Float-3.7e4 # Float0xFF # Fixnum given in hex1 + 1.0 # Float8
  10. 10. Strings• Enclosed in single or double quotes• Small differences between the two• String interpolation• Unicode escapes• Mutable objects"six times four is: #{6*4}"=> "six times four is: 24""this is a string"=> "this is a string"this is a string too=> "this is a string too""u20ac"=> "€"9
  11. 11. Arrays• Dynamically sized• Untyped and mutable• Example:[1, 2, 3] # an array with three Fixnum objects[] #empty array[0] * 10 # new array containing 10 zeros["a string", 42, 3.3, []] # can hold any type of objecta = [1, 1, 2, 3, 5, 8]a[0] # first element is 1a[-1] # last element is 8a[10] # nil if exceeding limitsa[7] = 21 # extends the array (with nil)a[2,3] # subarray starting from 2, 3 elements longa[2,3] = [A,B,C] #substitute subarraya + [0, -1] # concatenates two arrays[1, 2, 3, 4, 5] - [2, 4] # removes elements from the first array10
  12. 12. Hashes• Unordered collection of key-value pairs• Mutable• Indexed by keysa = {} # create an empty hasha[one] = 1 # map string one to Fixnum 1a[two] = 2# map string two to Fixnum 1a = {one => 1, two => 2} # create and initialize Hasha[one]=> 111
  13. 13. Symbols• Same as scheme symbols• Constant, immutable strings• I.e., placeholder for identifiers and strings• Always prefixed by a semicolon• Created in memory as soon as referenced:red # create a new symbol called red"blue".to_sym # convert a string to a symbol=> :blue:"red" # same as :redhash = {:red => "red", :blue => "blue" } # often used in hashes(i.e., fast)12
  14. 14. Boolean and Nil• true: logical true value• Singleton instance of TrueClass• false: logical false value• Singleton instance of FalseClass• nil: null value (i.e., absence of value)• Singleton instance of NilClass13
  15. 15. Rules for objects1. All variables are references to objects (there are noprimitive types!)2. Objects communicate via messages (i.e., method calls)3. Each object has its own (private) state4. Every object is an instance of a class14
  16. 16. Object References• It always works with references to object (i.e., similarto Scheme, Java)• Call by object sharing:• When an object is passed to a method, its referenceis passed (i.e., the reference is copied).s = "Ruby" # Creates a String object. Store the reference to it in st = s # Copy reference to tt[-1] = "" # Modify the object through reference to tprint s # Access (modified) object through st = "Java" # t now refers to a different objectprint s,t # Prints "RubJava"15
  17. 17. Classes and methods• class keyword to define a class• def to define methodsclass ClassName" def method1(par1, par2)" " expression1" end" def method2(par1, par2)" " expression2" endend16
  18. 18. Constructor and instancevariables• Method initialize is the constructor• Instance variables start with @ symbolclass Point" def initialize(x,y)" " @x = x" " @y = y" end" def to_s()" " return "#{@x},#{@y}"" endend17
  19. 19. Cleaner version...• Ruby supports “parallel assignments”• Return is implicit (i.e., like Scheme):• Last expression is returned if not specifiedclass Point" def initialize(x,y)" " @x, @y = x, y" end" def to_s()" " "#{@x},#{@y}"" endendInstance variables arecreated only when storedfor the first time18
  20. 20. Creating an object• Invoke constructor with newp = Point.new(10,20)• Invoking a method:print p.to_s• Sends the to_s message to object referenced by p19
  21. 21. Getters and Setters• Lets define getters and setters for Point classclass Point" def initialize(x,y)" " @x, @y = x, y" end" def x" " @x" end" def y" " @y" end" def x=(value)" " @x = value" end" def y=(value)" " @y = value" endendp = Point.new(10,20)p.y = 10 # notice the spacep.x= 20 #print p.x # same as p.x()print p.yLook like variable references.They are actually method calls(without parentheses)!20
  22. 22. Getters and Setters• Concise way to define getters and setters• Use symbols to identify the instance variableclass Point"" attr_accessor :x, :y" def initialize(x,y)" " @x, @y = x, y" endend• attr_accessor creates getters and setters• attr_reader creates getters only• attr_writer creates setters only21
  23. 23. Defining new operatorsclass Point" attr_accessor :x, :y" def initialize(x,y)" " @x, @y = x, y" end" def +(other)" " Point.new(@x + other.x, @y + other.y)" end" def -@ # Unary operator" " Point.new(-@x, -@y)" end" def *(scalar)" " Point.new(@x * scalar, @y * scalar)" endend+, - and * are justmethod names!22
  24. 24. ClassVariables andClass methods• Class variables are shared among allinstances of that class• Introduced with @@ prefix• Class methods are methodsassociated with a class (not with aninstance)• Introduced by prepending self. tothe method nameclass Point" attr_accessor :x, :y" @@total_points = 0" def initialize(x,y)" " @x, @y = x, y" " @@total_points += 1" end" def self.total_points" " @@total_points" endendp1 = Point.new(10,15)p2 = Point.new(20,30)print Point.total_points23
  25. 25. Inheritance• By default a class extends the Object class• Inherits all predefined methods• Classic subclass/superclass relationships• No multiple inheritance• Methods can be overridden• Instance variables are not inherited!class Point3D < Point" attr_accessor :z" def initialize(x,y,z)" " super(x,y)" " @z = z" end"end24
  26. 26. Modules• A container of:• Methods• Constants• Class variables• Modules cannot be instantiated• Effective way to create namespacesmodule Base64" DIGITS = (A..Z).to_a" def Base64.encode" end" def Base64.decode" endendBase64.encodeBase64.decodeBase64::DIGITS25
  27. 27. Nesting namespaces• Modules and classes can benested• Better readability and avoidname clashesmodule Base64" DIGITS = (A..Z).to_a" class Encoder" " def encode" " end" end" class Decoder" " def decoder" " end" endenda = Base64::Encoder.new26
  28. 28. Mixins• If module define some instance methods, they canbe “mixed-in” a class.• Mixin code can interact with code in the classmodule A" def a" endendmodule B" def b1" end" def b2" endendclass MyClass" include A" include B" def m" endendm = MyClass.newm.am.b1m.b227
  29. 29. Control structures• Classic control structures:• If, else, elsif, case, etc. (terminated with “end” keyword)• Plus some syntactic sugars:print "greater" if Math::PI > 3Conditional modifierUnlessunless Math::PI <= 3" print "greater"end28
  30. 30. Loops• Classic for, while, until, etc:• The object must have an each methodx = 0puts x += 1 while x < 10x = 0puts x += 1 until x >= 10array = [1,2,3,4]for element in array" puts elementendhash = {:a => 1, :b => 2, :c => 3}for key, value in hash" puts "#{key} => #{value}"endAlso with modifiers version of loops (one line)29
  31. 31. Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent element• Use yield to execute the passed block30
  32. 32. Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent element• Use yield to execute the passed block3.times{ puts "thank you!"}data.each{|x| puts x}[1,2,3].map{|x| x * x }factorial = 12.upto(n) {|x| factorial *= x}30
  33. 33. Iterators and yield• Allow to loop over a collection (or value)• Receive a block of code which is executed with thecurrent element• Use yield to execute the passed block3.times{ puts "thank you!"}data.each{|x| puts x}[1,2,3].map{|x| x * x }factorial = 12.upto(n) {|x| factorial *= x}30
  34. 34. Yield examplesdef my_method" yieldendmy_method{ puts "hello!"}Yield without parameters31
  35. 35. Yield examplesdef my_method" yieldendmy_method{ puts "hello!"}# This method expects a block.# It generates n values# of the form m*i + c for 0..n-1,# and yields them, one at a timedef sequence(n, m, c)" i = 0" while i < n" " yield m * i + c" " i += 1" endendsequence(5,3,20){|y| puts y}Yield without parameters Yield with parameters31
  36. 36. Blocks• Delimited with curly braces or do end keywords (i.e., multi line).• If method does not “yield”, the block is ignored.• Value returned from a block is the the value of the last expression.• Invoking return within a block returns from the calling method!def print_sequence" SPECIAL_VALUE = 5" s = sequence(5,3,20) do |y|" " if y == SPECIAL_VALUE" " " return 0" " end" " y * 2" end" print sendThe return statement exitsfrom the print_sequencemethod!32
  37. 37. Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:• Proc• Lambda• Invoke method call33
  38. 38. Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:• Proc• Lambda• Invoke method callp = Proc.new{|x,y| x + y}puts p.call(10,20)Creating a proc object33
  39. 39. Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:• Proc• Lambda• Invoke method callp = Proc.new{|x,y| x + y}puts p.call(10,20)Creating a proc objectl = lambda{|x,y| x + y}puts l.call(10,20)Creating a lambda object33
  40. 40. Procs and Lambdas• Blocks are syntactic structures• They are not objects!• However, it is possible to createblock objects:• Proc• Lambda• Invoke method callp = Proc.new{|x,y| x + y}puts p.call(10,20)Creating a proc objectl = lambda{|x,y| x + y}puts l.call(10,20)Creating a lambda objectGet the “arity” of a blockl = lambda{|x,y| x + y}puts l.arity=> 233
  41. 41. Converting blocks to procs• Blocks do not have a name• Blocks can be converted into proc• Use & (i.e., ampersand)# Explicit conversion into procdef sequence3(n, m, c, &b)" i=0" while(i < n)" " b.call(i*m + c)" " i += 1" endendsequence3(5, 2, 2) {|x| puts x }def sequence4(n, m, c, b)" i=0" while(i < n)" " b.call(i*m + c)" " i += 1" endendp = Proc.new {|x| puts x} # create procsequence4(5, 2, 2, p) # ordinary argument34
  42. 42. Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluation35
  43. 43. Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluationdef test" puts "entering method"" p = Proc.new { puts "entering proc"; return }" p.call # Invoking the proc makes method return" puts "exiting method" # This line is NEVER executedendReturn with proc35
  44. 44. Procs vs Lambdas• Lambda behave similar to method calls• Blocks behave similar to block evaluationdef test" puts "entering method"" p = Proc.new { puts "entering proc"; return }" p.call # Invoking the proc makes method return" puts "exiting method" # This line is NEVER executedenddef test" puts "entering method"" p = lambda { puts "entering lambda"; return }" p.call # Invoking the lambda does not make the methodreturn" puts "exiting method" # This line IS executedendReturn with procReturn with lambda35
  45. 45. References36

×