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. Exceptio...
Why Ruby… Ruby is simple and beautiful Variable declarations are unnecessary Easy to Learn. Variables are not typed M...
Where can we use Ruby….? System (n/w, RegExps) Web programming (using CGI) Agents, crawlers DB programming (using DBI)...
Running Ruby Code Run the interactive ruby shell – irb Run ruby from the command line – ruby Use the shebang! line on G...
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,Ru...
Methods Methods are defined with the def keyword followed by the method name andan optional list of parameter names in pa...
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_ss...
Ranges Inclusive rangemy_range = 1 .. 3my_range = abc .. abf Non-inclusive rangemy_range = 1 … 5my_range = abc … abf„Rub...
Hashes Hashes (sometimes known asassociative arrays, maps, ordictionaries) are similar toarrays in that they areindexed c...
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_s...
Example Using Strings:person1 = { “name” => "Fred", “age” => 20, “gender” => “male” }person2 = { “name” => "Laura", “age”...
Blocks Chunks of code between braces orbetween do- endEg:5.times doputs "Blocks are powerful"endBlocks With parametersdef...
Operators Unary (+ and -) Exponentiation (**) Arithmetic (=,-,*,/,%) Logical (~, &, |, ^) Equality (==, !=, =~, !~, =...
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 onl...
Unless Executes code only if an associatedexpression evaluates to false or nil.SYNTAX:# single-way unless statementunless...
Case Multiway conditionalname = case name = if x == 1 then "one"when x == 1 then "one" elsif x == 2 then "two"when x == 2...
While Execute a chunk of code while acertain condition is true, or untilthe condition becomes true. The loop condition i...
For/in Executes code once for each elementin expression.Syntax:for variable_name in rangecode blockendEg:for i in 0..9pri...
Class A class is an expanded concept of a data structure: instead of holding onlydata, it can hold both data and function...
Objects A class provides the blueprints for objects, so basically an object is createdfrom a class. We declare objects of...
INITIALIZE METHOD The initialize method is a standard Ruby class method and works almost sameway as constructor works in ...
Example-Classes & Objectsclass BankAccountdef interest_rate@@interest_rate = 0.2enddef calc_interest ( balance )puts balan...
Encapsulation Ability for an object to have certain methods and attributesavailable for use publicly (from any section of...
Egclass Persondef initialize(name)set_name(name)enddef name@first_name +   + @last_nameendprivatedef set_name(name)first_n...
Inheritance Allows us to define a class in terms of another class, which makes it easierto create and maintain an applica...
Example-Inheritanceclass My_classdef print_foo()print "I Love Ruby!"endendclass Derived_class < My_classdef initialize()@a...
Mixins A specialized implementation of multiple inheritance in which only the interfaceportion is inherited.Eg:module Ade...
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 r...
Method Overridingclass Boxdef initialize(w,h)@width, @height = w, henddef getArea@width * @heightendendclass BigBox < Boxd...
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…??
Upcoming SlideShare
Loading in...5
×

Ruby Basics

366

Published on

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

  • Be the first to like this

No Downloads
Views
Total Views
366
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ruby Basics

  1. 1. Ruby
  2. 2. Ruby is... A dynamic Open source Object oriented Interpreted Scripting Language
  3. 3. 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.
  4. 4. Why Ruby… Ruby is simple and beautiful Variable declarations are unnecessary Easy to Learn. Variables are not typed Memory management is automatic
  5. 5. Where can we use Ruby….? System (n/w, RegExps) Web programming (using CGI) Agents, crawlers DB programming (using DBI) GUI (Tk, RubyMagick)
  6. 6. Running Ruby Code Run the interactive ruby shell – irb Run ruby from the command line – ruby Use the shebang! line on GNU/Linux
  7. 7. Lets get started….puts Hello, world!p Hello, world! # prints with newlinemy_var = gets # get input
  8. 8. 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
  9. 9. 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
  10. 10. Basic data types Numbers Strings Ranges Arrays Hashes Boolean
  11. 11. NumbersNumbersIntegers FloatFixnum Bignum(Numbers between-2^62 & 2^62-1or-2^30 & 2^30-1)
  12. 12. 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
  13. 13. 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 )
  14. 14. 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
  15. 15. Boolean• true• falseAny value evaluate to true, only nilevaluate to false.
  16. 16. 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
  17. 17. 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 }
  18. 18. 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
  19. 19. Operators Unary (+ and -) Exponentiation (**) Arithmetic (=,-,*,/,%) Logical (~, &, |, ^) Equality (==, !=, =~, !~, ===) Comparison (<, <=, >, >=, <=>) Boolean (&&, ||, !, and, or, not) Conditional (?:) Assignment (+=,-=,*=,/=)
  20. 20. Control structuresConditional Loops*If *for*Unless *while and until*case
  21. 21. 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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)
  30. 30. 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.
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. Mixins A specialized implementation of multiple inheritance in which only the interfaceportion is inherited.Eg:module Adef a1enddef a2endendmodule Bdef b1end
  35. 35. Mixins(Cont..)def a2endendclass Sampleinclude Ainclude Bdef s1endsamp=Sample.newsamp.a1samp.a2samp.b1samp.b2samp.s1
  36. 36. 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
  37. 37. 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()
  38. 38. Operator overloadingclass Tester1def initialize x@x = xenddef +(y)@x + yendenda = Tester1.new 5puts(a + 3)a += 7puts a
  39. 39. Advantages Better Access Control Portable and extensible with third-party library Interactive environment
  40. 40. Queries…??

×