Introduction to Ruby

Post on 17-May-2015

1.246 views 0 download

Tags:

description

an introduction to ruby programming language. This is a start for peoples those who start ruby on rails

Transcript of Introduction to Ruby

Ruby ProgrammingRuby Programming

#

What is Ruby ?What is Ruby ?

• Ruby – Object Oriented Programming Ruby – Object Oriented Programming LanguageLanguage

• Written 1995 by Yukihiro MatsumotoWritten 1995 by Yukihiro Matsumoto• Influenced by Python,Pearl,LISPInfluenced by Python,Pearl,LISP• Easy to understand and workwithEasy to understand and workwith• Simple and nice syntaxSimple and nice syntax• Powerful programming capabilitiesPowerful programming capabilities

AdvantagesAdvantages

• Powerful And ExpressivePowerful And Expressive• Rich Library SupportRich Library Support• Rapid DevelopmentRapid Development• Open SourceOpen Source• Flexible and DynamicFlexible and Dynamic

#

Install RubyInstall Ruby

• On FedoraOn Fedora– Rpms are availableRpms are available

• ruby-1.8.6.287-8.fc11.i586ruby-1.8.6.287-8.fc11.i586• ruby-develruby-devel• ruby-postgresruby-postgres• ruby-docsruby-docs• ruby-raccruby-racc• ruby-docsruby-docs

#

TypesTypes

• Command “ruby”Command “ruby”• The extension is .rbThe extension is .rb

#

Ruby DocumentsRuby Documents

• Command riCommand ri• ExampleExample

– ri classri class–

#

helloPerson.rbhelloPerson.rb

• # First ruby programme# First ruby programme• def helloPerson(name)def helloPerson(name)• result = "Hello, " + nameresult = "Hello, " + name• return resultreturn result• endend• puts helloPerson("Justin")puts helloPerson("Justin")

#

Execute ProgrammeExecute Programme

• $ ruby helloPerson.rb$ ruby helloPerson.rb•• Nice and simpleNice and simple• Can use irb – interactive ruby shellCan use irb – interactive ruby shell• # is for comments like //# is for comments like //

Hello, Justin

#

Ruby variablesRuby variables

• def returnFoodef returnFoo• bar = "Ramone, bring me my cup."bar = "Ramone, bring me my cup."• return barreturn bar• endend• puts returnFooputs returnFoo•

#

Kinds of VariablesKinds of Variables

• Global variable - $ signGlobal variable - $ sign• instance variable - @ signinstance variable - @ sign• Class Variable - @@ signClass Variable - @@ sign• Local Variable – no signLocal Variable – no sign• Constants – Capital LettersConstants – Capital Letters

#

Global VariableGlobal Variable

• Available everywhere inside a Available everywhere inside a programmeprogramme

• Not use frequentlyNot use frequently

#

instance variableinstance variable

• Unique inside an instance of a classUnique inside an instance of a class• Truncated with instanceTruncated with instance• @apple = Apple.new@apple = Apple.new• @apple.seeds = 15@apple.seeds = 15• @apple.color = "Green"@apple.color = "Green"•

#

ClassesClasses• class Courseclass Course

• def initialize(dept, number, name, professor)def initialize(dept, number, name, professor)

• @dept = dept@dept = dept

• @number = number@number = number

• @name = name@name = name

• @professor = professor@professor = professor

• endend

• def to_sdef to_s

• "Course Information: #@dept #@number - #@name [#@professor]""Course Information: #@dept #@number - #@name [#@professor]"

• endend

• defdef

• self.find_all_studentsself.find_all_students

• ......

• endend

• endend

#

ClassesClasses

• Initialize – is the constructorInitialize – is the constructor• Def – end -> functionDef – end -> function• Class-end -> classClass-end -> class

#

Define ObjectDefine Object• class Studentclass Student

• def login_studentdef login_student

• puts "login_student is running"puts "login_student is running"

• endend

• privateprivate

• def delete_studentsdef delete_students

• puts "delete_students is running"puts "delete_students is running"

• endend

• protectedprotected

• def encrypt_student_passworddef encrypt_student_password

• puts "encrypt_student_password is running"puts "encrypt_student_password is running"

• endend

• endend

#

Define ObjectDefine Object

• @student = Student.new@student = Student.new• @student.delete_students # This will fail@student.delete_students # This will fail• Because it is privateBecause it is private•

#

Classes consist of methods Classes consist of methods and instance variablesand instance variables

• class Coordinateclass Coordinate

• def initialize(x,y) #constructordef initialize(x,y) #constructor

• @x = x # set instance variables@x = x # set instance variables

• @y = y@y = y

• endend

• def to_s # string representationdef to_s # string representation

• "(#{@x},#{@y})""(#{@x},#{@y})"

• endend

• endend

• point = Coordinate.new(1,5)point = Coordinate.new(1,5)

• puts pointputs point

• Will output (1,5)Will output (1,5)

#

InheritanceInheritance• class AnnotatedCoordinate < Coordinateclass AnnotatedCoordinate < Coordinate

• def initialize(x,y,comment)def initialize(x,y,comment)

• super(x,y)super(x,y)

• @comment = comment@comment = comment

• endend

• def to_sdef to_s

• super + "[#@comment]"super + "[#@comment]"

• endend

• EndEnd

• a_point =a_point =

• AnnotatedCoordinate.new(8,14,"Centre");AnnotatedCoordinate.new(8,14,"Centre");

• puts a_pointputs a_point

• Out Put Is -> (8,14)[Centre]Out Put Is -> (8,14)[Centre]

#

InheritanceInheritance

• Inherit a parent classInherit a parent class• Extend functions and variablesExtend functions and variables• Add more features to base classAdd more features to base class

#

PolymorphismPolymorphism

• The behavior of an object that varies The behavior of an object that varies depending on the input.depending on the input.

••

#

PolymorphismPolymorphism• class Personclass Person

• # Generic features# Generic features

• endend

• class Teacher < Personclass Teacher < Person

• # A Teacher can enroll in a course for a semester as either# A Teacher can enroll in a course for a semester as either

• # a professor or a teaching assistant# a professor or a teaching assistant

• def enroll(course, semester, role)def enroll(course, semester, role)

• ......

• endend

• endend

• class Student < Personclass Student < Person

• # A Student can enroll in a course for a semester# A Student can enroll in a course for a semester

• def enroll(course, semester)def enroll(course, semester)

• ......

• endend

• endend

#

Calling objectsCalling objects

• @course1 = Course.new("CPT","380","Beginning @course1 = Course.new("CPT","380","Beginning Ruby Programming","Lutes")Ruby Programming","Lutes")

• @course2 = GradCourse.new("CPT","499d","Small @course2 = GradCourse.new("CPT","499d","Small Scale Digital Imaging","Mislan", "Spring")Scale Digital Imaging","Mislan", "Spring")

• p @course1.to_sp @course1.to_s

• p @course2.to_sp @course2.to_s

#

Calling ObjectsCalling Objects

• @course1 that contains information @course1 that contains information about a Courseabout a Course

• @course2 is another instance variable, @course2 is another instance variable, but it contains information about a but it contains information about a GradClass objectGradClass object

#

Arrays and hashesArrays and hashes

• fruit = ['Apple', 'Orange', 'Squash']fruit = ['Apple', 'Orange', 'Squash']• puts fruit[0]puts fruit[0]• fruit << 'Corn'fruit << 'Corn'• puts fruit[3]puts fruit[3]

#

ArraysArrays

• << will input a new element<< will input a new element• Last line outputs the new elementLast line outputs the new element

#

Arrays More...Arrays More...

• fruit = {fruit = {• :apple => 'fruit',:apple => 'fruit',• :orange => 'fruit',:orange => 'fruit',• :squash => 'vegetable':squash => 'vegetable'• }}• puts fruit[:apple]puts fruit[:apple]• fruit[:corn] = 'vegetable'fruit[:corn] = 'vegetable'• puts fruit[:corn]puts fruit[:corn]

#

Arrays More...Arrays More...

• h = {"Red" => 1, "Blue" => 2, "Green" => h = {"Red" => 1, "Blue" => 2, "Green" => 3}3}

• CORPORATECORPORATE• p h["Red"]p h["Red"]• Outpus -> 1Outpus -> 1• h["Yellow"] = 4h["Yellow"] = 4• p h["Yellow"]p h["Yellow"]• Outputs -> 4Outputs -> 4

#

Decision structuresDecision structures• age = 40age = 40

• if age < 12if age < 12

• puts "You are too young to play"puts "You are too young to play"

• elsif age < 30elsif age < 30

• puts "You can play for the normal price"puts "You can play for the normal price"

• elsif age == 35elsif age == 35

• puts "You can play for free"puts "You can play for free"

• elsif age < 65elsif age < 65

• puts "You get a senior discount"puts "You get a senior discount"

• elseelse

• puts "You are too old to play"puts "You are too old to play"

• endend

#

whilewhile

• clock = 0clock = 0• while clock < 90while clock < 90• puts "I kicked the ball to my team mate puts "I kicked the ball to my team mate

in the " + count.to_s + "in the " + count.to_s + "• minute of the match."minute of the match."• clock += 1clock += 1• endend

#

IteratorsIterators

• fruit = ['Apple', 'Orange', 'Squash']fruit = ['Apple', 'Orange', 'Squash']• fruit.each do |f|fruit.each do |f|• puts fputs f• endend

#

IteratorsIterators

• Keyword - do -Keyword - do -• Instance variable |f|Instance variable |f|• Print f means print the instance of the Print f means print the instance of the

looploop

#

IteratorsIterators

• fruit = ['Apple', 'Orange', 'Squash']fruit = ['Apple', 'Orange', 'Squash']• fruit.each_with_index do |f,i|fruit.each_with_index do |f,i|• puts "#{i} is for #{f}"puts "#{i} is for #{f}"• endend•

#

IteratorsIterators

• Here f is the instance Here f is the instance • Index is iIndex is i• Will get two variables Will get two variables

#

IteratorsIterators

• fruit = ['Apple', 'Orange', 'Squash']fruit = ['Apple', 'Orange', 'Squash']• for i in 0...fruit.lengthfor i in 0...fruit.length• puts fruit[i]puts fruit[i]• endend•

#

IteratorsIterators

• For loopFor loop• Same old syntaxSame old syntax• But 'each' loop is smart to handle an But 'each' loop is smart to handle an

arrayarray• 'each' dont need a max cutoff value.'each' dont need a max cutoff value.

#

case...whencase...when• temperature = -88temperature = -88

• case temperaturecase temperature

• when -20...0when -20...0

• puts "cold“; start_heaterputs "cold“; start_heater

• when 0...20when 0...20

• puts “moderate"puts “moderate"

• when 11...30when 11...30

• puts “hot”; drink_beerputs “hot”; drink_beer

• elseelse

• puts "are you serious?"puts "are you serious?"

• endend

#

Exception handlingException handling

• beginbegin• @user = User.find(1)@user = User.find(1)• @user.name@user.name• rescuerescue• STDERR.puts "A bad error occurred"STDERR.puts "A bad error occurred"• endend•

#

ThanksThanks