• Save
Ruby Basics
Upcoming SlideShare
Loading in...5

Ruby Basics






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

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.

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

    Ruby Basics Ruby Basics Presentation Transcript

    • Ruby
    • Ruby is... A dynamic Open source Object oriented Interpreted Scripting Language
    • Ruby: the Language No multiple inheritance, but modules allow theimporting of methods. Has garbage collection. Exception handling, like Java. Any class or instance can be extended anytime(even during runtime) Allows operator overloading.
    • Why Ruby… Ruby is simple and beautiful Variable declarations are unnecessary Easy to Learn. Variables are not typed Memory management is automatic
    • Where can we use Ruby….? System (n/w, RegExps) Web programming (using CGI) Agents, crawlers DB programming (using DBI) GUI (Tk, RubyMagick)
    • Running Ruby Code Run the interactive ruby shell – irb Run ruby from the command line – ruby Use the shebang! line on GNU/Linux
    • Lets get started….puts Hello, world!p Hello, world! # prints with newlinemy_var = gets # get input
    • Variables No need to pre declare variables @ - instance variables (If you refer to an uninitialized instance variable,Ruby returns nil.) @@ - class variables (Class variables must always have a value assigned tothem before they are used.Will raise NameError if it is uninitialized) $ - global variables
    • Methods Methods are defined with the def keyword followed by the method name andan optional list of parameter names in parentheses. The Ruby code that constitutes the method body follows the parameter list,and the end of the method is marked with the end keyword. Parameter names can be used as variables within the method body, and thevalues of these named parameters come from the arguments to a methodinvocation.Syntax:def functioname (parameter list)body of the functionend
    • Basic data types Numbers Strings Ranges Arrays Hashes Boolean
    • NumbersNumbersIntegers FloatFixnum Bignum(Numbers between-2^62 & 2^62-1or-2^30 & 2^30-1)
    • Stringss = „This is a new string „earl = ”Earl”s = “My name is #{earl}”answer = 42s = „The answer name is „ + answer.to_sstr = “Another string”str = %q[String]str = %Q[Another string]str = <<EOFLong long longmultiline textEOF
    • Ranges Inclusive rangemy_range = 1 .. 3my_range = abc .. abf Non-inclusive rangemy_range = 1 … 5my_range = abc … abf„Ruby allows us to use ranges in a varietyof ways:• Sequences (1..100)• Conditions (result = case scorewhen 0..40: "Fail"when 41..60: "Pass“ )• Intervals (if ((1..10) === 5)puts "5 lies in (1..10)"end )
    • Hashes Hashes (sometimes known asassociative arrays, maps, ordictionaries) are similar toarrays in that they areindexed collections ofobject references. Can index a hash withobjects of any type: strings,regular expressions, and soon. Eg: my_hash = {desc => {color =>blue,},1 => [1, 2, 3]} print my_hash[desc][color]will returnblue
    • Boolean• true• falseAny value evaluate to true, only nilevaluate to false.
    • Symbols An identifier whose first character is acolon ( : ) Symbol is not ->string ->variable ->constant Egcurrent_situation = :goodputs "Everything is fine" if current_situation == :goodputs "PANIC!" if current_situation == :bad
    • Example Using Strings:person1 = { “name” => "Fred", “age” => 20, “gender” => “male” }person2 = { “name” => "Laura", “age” => 23, “gender” => “female” } Using Symbolsperson1 = { :name => "Fred", :age => 20, :gender => :male }person2 = { :name => "Laura", :age => 23, :gender => :female }
    • Blocks Chunks of code between braces orbetween do- endEg:5.times doputs "Blocks are powerful"endBlocks With parametersdef this_many_times(num)counter = 0while counter < numyieldcounter += 1endendthis_many_times(5) doputs "Blocks are powerful"end
    • Operators Unary (+ and -) Exponentiation (**) Arithmetic (=,-,*,/,%) Logical (~, &, |, ^) Equality (==, !=, =~, !~, ===) Comparison (<, <=, >, >=, <=>) Boolean (&&, ||, !, and, or, not) Conditional (?:) Assignment (+=,-=,*=,/=)
    • Control structuresConditional Loops*If *for*Unless *while and until*case
    • If and If…elseSYNTAX: if expression if expressioncode codeend elseend The code between if and end isexecuted if (and only if) the expressionevaluates to something other thanfalse or nil.Eg:if num > 0print “num > 0”elsif num < 0print “num < 0”elseprint “num = 0”end
    • Unless Executes code only if an associatedexpression evaluates to false or nil.SYNTAX:# single-way unless statementunless conditioncodeend# two-way unless statementunless conditioncodeelsecodeendEg:unless num == 0print “num not equals0”elseprint “num equals 0”end
    • Case Multiway conditionalname = case name = if x == 1 then "one"when x == 1 then "one" elsif x == 2 then "two"when x == 2 then "two" elsif x == 3 then "three"when x == 3 then "three" elsif x == 4 then "four"when x == 4 then "four" else "many"else "many" endend
    • While Execute a chunk of code while acertain condition is true, or untilthe condition becomes true. The loop condition is the Booleanexpression that appears betweenthe while or until and dokeywords. While loop executes its body if thecondition evaluated is true and Unless loop is executed if thecondition evaluates to false or nil. Eg:#Print from 10 to 0 using whilex = 10 # Initialize a loop counter variablewhile x >= 0 do # Loop while x is greater than or equal to 0puts x # Print out the value of xx = x - 1 # Subtract 1 from xend # The loop ends here# Count back up to 10 using an until loopx = 0 # Start at 0 (instead of -1)until x > 10 do # Loop until x is greater than 10puts xx = x + 1end # Loop ends here
    • For/in Executes code once for each elementin expression.Syntax:for variable_name in rangecode blockendEg:for i in 0..9print i, “ ”end#=> 0 1 2 3 4 5 6 7 8 9
    • Class A class is an expanded concept of a data structure: instead of holding onlydata, it can hold both data and functions. A template definition of the methods and variables in a particular kind ofobject In ruby,the first letter of the class name must be in upper case Syntaxclass class_nameclass members declaration and definitionend
    • Objects A class provides the blueprints for objects, so basically an object is createdfrom a class. We declare objects of a class using new keyword. Syntax:obj_name=classname.new Eg:circle=Shape.new
    • INITIALIZE METHOD The initialize method is a standard Ruby class method and works almost sameway as constructor works in other object oriented programming languages. Useful when you want to initialize some class variables at the time of objectcreation.Eg:def initialize(length,breadth)@l=length@b=breadthend
    • Example-Classes & Objectsclass BankAccountdef interest_rate@@interest_rate = 0.2enddef calc_interest ( balance )puts balance * interest_rateenddef accountNumber@accountNumberputs "account number is : #{@accountNumber}"endendaccount = BankAccount.new()account.calc_interest( 1000 )account.accountNumber(70)
    • Encapsulation Ability for an object to have certain methods and attributesavailable for use publicly (from any section of code), but for othersto be visible only within the class itself or by other objects of thesame class.
    • Egclass Persondef initialize(name)set_name(name)enddef name@first_name + + @last_nameendprivatedef set_name(name)first_name, last_name = name.split(/s+/)set_first_name(first_name)set_last_name(last_name)enddef set_first_name(name)@first_name = nameenddef set_last_name(name)@last_name = nameendendp = Person.new("Fred Bloggs")p.set_last_name("Smith")puts p.name
    • Inheritance Allows us to define a class in terms of another class, which makes it easierto create and maintain an application. Provides an opportunity to reuse the code functionality and fastimplementation tim Ruby does not support Multiple level of inheritances but Ruby supportsmixins.Syntax:class der_class_name < base_class_name
    • Example-Inheritanceclass My_classdef print_foo()print "I Love Ruby!"endendclass Derived_class < My_classdef initialize()@arg = "I Love Ruby!"enddef print_arg()print @argendendmy_object = Derived_class.newmy_object.print_fooMy_object.print_arg
    • Mixins A specialized implementation of multiple inheritance in which only the interfaceportion is inherited.Eg:module Adef a1enddef a2endendmodule Bdef b1end
    • Mixins(Cont..)def a2endendclass Sampleinclude Ainclude Bdef s1endsamp=Sample.newsamp.a1samp.a2samp.b1samp.b2samp.s1
    • Polymorphism Allows a object to accept different requests of a client andresponds according to the current state of the runtime system, allwithout bothering the user. Does not supports method overloading. Methods can be overridden
    • Method Overridingclass Boxdef initialize(w,h)@width, @height = w, henddef getArea@width * @heightendendclass BigBox < Boxdef getArea@area = @width * @heightputs "Big box area is : #@area"endendbox = BigBox.new(10, 20)box.getArea()
    • Operator overloadingclass Tester1def initialize x@x = xenddef +(y)@x + yendenda = Tester1.new 5puts(a + 3)a += 7puts a
    • Advantages Better Access Control Portable and extensible with third-party library Interactive environment
    • Queries…??