SlideShare a Scribd company logo
Introduction To Ruby
     Programming



    Bindesh Vijayan
Ruby as OOPs
●   Ruby is a genuine Object
    oriented programming
●   Everything you manipulate is an
    object
●   And the results of the
    manipulation is an object
●   e.g. The number 4,if used, is an
    object
        Irb> 4.class      Python : len()
           Fixnum        Ruby: obj.length
Setting up and installing ruby
●   There are various ways of
    installing ruby
    ●   RailsInstaller for windows and osx
        (http://railsinstaller.org)
    ●   Compiling from source
    ●   Using a package manager like
        rvm..most popular
Ruby version
           manager(rvm)
●   In the ruby world, rvm is the most
    popular method to install ruby and
    rails
●   Rvm is only available for mac os
    x,linux and unix
●   Rvm allows you to work with
    multiple versions of ruby
●   To install rvm you need to have
    the curl program installed
Installing rvm(linux)
$ sudo apt-get install curl


$ curl -L https://get.rvm.io | bash -s stable –ruby


$ rvm requirements


$ rvm install 1.9.3
Standard types - numbers
●   Numbers
    ●   Ruby supports integers and floating point
        numbers
    ●    Integers within a certain range (normally
        -230 to 230-1 or -262 to 262-1) are held
        internally in binary form, and are objects
        of class Fixnum
    ●   Integers outside the above range are
        stored in objects of class Bignum
    ●   Ruby automatically manages the
        conversion of Fixnum to Bignum and vice
        versa
    ●   Integers in ruby support several types
        of iterators
Standard types- numbers
●   e.g. Of iterators
    ●   3.times          {   print "X " }
    ●   1.upto(5)        {   |i| print i, " " }
    ●   99.downto(95)    {   |i| print i, " " }
    ●   50.step(80, 5)   {   |i| print i, " " }
Standard types - strings
●   Strings in ruby are simply a sequence of
    8-bit bytes
●   In ruby strings can be assigned using
    either a double quotes or a single quote
    ●   a_string1 = 'hello world'
    ●   a_string2 = “hello world”
●   The difference comes
●    when you want to use a special
    character e.g. An apostrophe
    ●   a_string1 = “Binn's world”
    ●   a_string2 = 'Binn's world' # you need to
        use an escape sequence here
Standard types - string
●   Single quoted strings only
    supports 2 escape sequences, viz.
     ●   ' - single quote
     ●    - single backslash
●   Double quotes allows for many
    more escape sequences
●   They also allow you to embed
    variables or ruby code commonly
    called as interpolation
    puts "Enter name"
    name = gets.chomp
    puts "Your name is #{name}"
Standard types - string
Common escape sequences available are :

  ●   "   –   double quote
  ●      –   single backslash
  ●   a   –   bell/alert
  ●   b   –   backspace
  ●   r   –   carriage return
  ●   n   –   newline
  ●   s   –   space
  ●   t   –   tab
  ●
Working with strings
gsub              Returns a copy of str with            str.gsub( pattern,
                  all occurrences of pattern            replacement )
                  replaced with either
                  replacement or the value of
                  the block.
chomp             Returns a new String with             str.chomp
                  the given record separator
                  removed from the end of str
                  (if present).
count             Return the count of                   str.count
                  characters inside string
strip             Removes leading and                   str.strip
                  trailing spaces from a
                  string
to_i              Converts the string to a              str.to_i
                  number(Fixnum)
upcase            Upcases the content of the            str.upcase
                  strings

  http://www.ruby-doc.org/core-1.9.3/String.html#method-i-strip
Standard types - ranges
●   A Range represents an interval—a set of
    values with a start and an end
●   In ruby, Ranges may be constructed using
    the s..e and s...e literals, or with
    Range::new
●   ('a'..'e').to_a    #=> ["a", "b", "c",
    "d", "e"]
●   ('a'...'e').to_a   #=> ["a", "b", "c",
    "d"]
Using ranges
●   Comparison
    ●   (0..2) == (0..2)           #=>
        true
    ●   (0..2) == Range.new(0,2)   #=>
        true
    ●   (0..2) == (0...2)          #=>
        false
Using ranges
●   Using in iteration
     (10..15).each do |n|
        print n, ' '
     end
Using ranges
●   Checking for members
    ●   ("a".."z").include?("g")   # -> true
    ●   ("a".."z").include?("A")   # ->
        false
Methods
●   Methods are defined using the def
    keyword
●   By convention methods that act as a
    query are often named in ruby with a
    trailing '?'
    ●   e.g. str.instance_of?
●   Methods that might be
    dangerous(causing an exception e.g.)
    or modify the reciever are named with
    a trailing '!'
    ●   e.g.   user.save!
●   '?' and '!' are the only 2 special
    characters allowed in method name
Defining methods
●   Simple method:
     def mymethod
     end
●   Methods with arguments:
     def mymethod2(arg1, arg2)
     end
●   Methods with variable length arguments
     def varargs(arg1, *rest)
       "Got #{arg1} and #{rest.join(', ')}"
     end
Methods
●   In ruby, the last line of the
    method statement is returned back
    and there is no need to explicitly
    use a return statement
     def get_message(name)
       “hello, #{name}”
       end
.Calling a method :
     get_message(“bin”)
●   Calling a method without arguments
    :
     mymethod #calls the method
Methods with blocks
●   When a method is called, it can be given
    a random set of code to be executed
    called as blocks
     def takeBlock(p1)
         if block_given?
              yield(p1)
       else
             p1
      end
     end
Calling methods with
        blocks
takeBlock("no block") #no block
provided
takeBlock("no block") { |s|
s.sub(/no /, '') }
Classes
●   Classes in ruby are defined by
    using the keyword 'class'
●   By convention, ruby demands that
    the class name should be capital
●   An initialize method inside a
    class acts as a constructor
●   An instance variable can be
    created using @
class
SimpleClass

end


//instantiate an
object

s1 =
SimpleClass.new




class Book

      def intitialize(title,author)
       @title = title
       @author = author
       end
end



//creating an object of the class

b1 = Book.new("programming ruby","David")
Making an attribute
           accessible
●   Like in any other object oriented
    programming language, you will need
    to manipulate the attributes
●   Ruby makes this easy with the
    keyword 'attr_reader' and
    'attr_writer'
●   This defines the getter and the
    setter methods for the attributes
class Book

 attr_reader :title, :author

 def initialize(title,author)
   @title = title
   @author = author
 end

end

#using getters
CompBook = Book.new(“A book”, “me”)
Puts CompBook.title
Symbols
●   In ruby symbols can be declared using ':'
●   e.g :name
●   Symbols are a kind of strings
●   The important difference is that they are immutable
    unlike strings
●   Mutable objects can be changed after assignment while
    immutable objects can only be overwritten.
    ●   puts "hello" << " world"
    ●   puts :hello << :" world"
Making an attribute
        writeable
class Book

 attr_writer :title, :author
 def initialize(title,author)
   @title = title
   @author = author
 end

end
myBook = Book.new("A book",
"author")

myBook.title = "Some book"
Class variables
●   Sometimes you might need to declare a
    class variable in your class definition
●   Class variables have a single copy for
    all the class objects
●   In ruby, you can define a class variable
    using @@ symbol
●   Class variables are private to the class
    so in order to access them outside the
    class you need to defined a getter or a
    class method
Class Methods
●   Class methods are defined using
    the keyword self
●   e.g.
      –   def self. myclass_method
          end
Example
class SomeClass
   @@instance = 0 #private
   attr_reader :instance

  def initialize
     @@instance += 1
  end

   def self.instances
      @@instance
   end
end

s1 = SomeClass.new
s2 = SomeClass.new

puts "total instances #{SomeClass.instances}"
Access Control
●   You can specify 3 types of
    access control in ruby
    ●   Private
    ●   Protected
    ●   Public
●   By default, unless specified,
    all methods are public
Access Control-Example
 class Program

       def get_sum
           calculate_internal
       end

 private
    def calculate_internal
    end

 end

More Related Content

What's hot

Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
Giuseppe Arici
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
Sumant Tambe
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
Giuseppe Arici
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
Aleš Najmann
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
kim.mens
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) Programmers
ZendCon
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
Kürşad Gülseven
 
Hot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingHot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments Passing
Andrey Upadyshev
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
Andrey Upadyshev
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
Pierre de Lacaze
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
Alex Navis
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
Andrey Upadyshev
 

What's hot (20)

Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Open MP cheet sheet
Open MP cheet sheetOpen MP cheet sheet
Open MP cheet sheet
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) Programmers
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
Hot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingHot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments Passing
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages8 - OOP - Syntax & Messages
8 - OOP - Syntax & Messages
 

Viewers also liked

Programming Language: Ruby
Programming Language: RubyProgramming Language: Ruby
Programming Language: Ruby
Hesham Shabana
 
Design of a secure "Token Passing" protocol
Design of a secure "Token Passing" protocolDesign of a secure "Token Passing" protocol
Design of a secure "Token Passing" protocol
Augusto Ciuffoletti
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
Tushar Pal
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingWen-Tien Chang
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Wen-Tien Chang
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upWen-Tien Chang
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
Ranjith Siji
 
Customer Scale: Stateless Sessions and Managing High-Volume Digital Services
Customer Scale: Stateless Sessions and Managing High-Volume Digital ServicesCustomer Scale: Stateless Sessions and Managing High-Volume Digital Services
Customer Scale: Stateless Sessions and Managing High-Volume Digital Services
ForgeRock
 
OAuth 2.0 Token Exchange: An STS for the REST of Us
OAuth 2.0 Token Exchange: An STS for the REST of UsOAuth 2.0 Token Exchange: An STS for the REST of Us
OAuth 2.0 Token Exchange: An STS for the REST of Us
Brian Campbell
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
Wen-Tien Chang
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事Wen-Tien Chang
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
Wen-Tien Chang
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
Mike Bowler
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
Wen-Tien Chang
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
Wen-Tien Chang
 
從零開始的爬蟲之旅 Crawler from zero
從零開始的爬蟲之旅 Crawler from zero從零開始的爬蟲之旅 Crawler from zero
從零開始的爬蟲之旅 Crawler from zero
Shi-Ken Don
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
Wen-Tien Chang
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩Wen-Tien Chang
 

Viewers also liked (20)

Programming Language: Ruby
Programming Language: RubyProgramming Language: Ruby
Programming Language: Ruby
 
Design of a secure "Token Passing" protocol
Design of a secure "Token Passing" protocolDesign of a secure "Token Passing" protocol
Design of a secure "Token Passing" protocol
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Customer Scale: Stateless Sessions and Managing High-Volume Digital Services
Customer Scale: Stateless Sessions and Managing High-Volume Digital ServicesCustomer Scale: Stateless Sessions and Managing High-Volume Digital Services
Customer Scale: Stateless Sessions and Managing High-Volume Digital Services
 
OAuth 2.0 Token Exchange: An STS for the REST of Us
OAuth 2.0 Token Exchange: An STS for the REST of UsOAuth 2.0 Token Exchange: An STS for the REST of Us
OAuth 2.0 Token Exchange: An STS for the REST of Us
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
 
從零開始的爬蟲之旅 Crawler from zero
從零開始的爬蟲之旅 Crawler from zero從零開始的爬蟲之旅 Crawler from zero
從零開始的爬蟲之旅 Crawler from zero
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
 

Similar to Ruby training day1

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation
platico_dev
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
AbdulRazaqAnjum
 
Ruby
RubyRuby
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
Kirk Kimmel
 
Linux shell
Linux shellLinux shell
Linux shell
Kenny (netman)
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1Brady Cheng
 
Python intro
Python introPython intro
Python intro
Abhinav Upadhyay
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
NiladriDey18
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshop
Adam Davis
 
C tour Unix
C tour UnixC tour Unix
C tour Unix
Melvin Cabatuan
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introduction
ASIT Education
 
Sdl Basic
Sdl BasicSdl Basic
Sdl Basic
roberto viola
 
Dart workshop
Dart workshopDart workshop
Dart workshop
Vishnu Suresh
 

Similar to Ruby training day1 (20)

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Ruby
RubyRuby
Ruby
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
 
Linux shell
Linux shellLinux shell
Linux shell
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
Python intro
Python introPython intro
Python intro
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshop
 
C tour Unix
C tour UnixC tour Unix
C tour Unix
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introduction
 
Sdl Basic
Sdl BasicSdl Basic
Sdl Basic
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 

Recently uploaded

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 

Recently uploaded (20)

Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 

Ruby training day1

  • 1. Introduction To Ruby Programming Bindesh Vijayan
  • 2. Ruby as OOPs ● Ruby is a genuine Object oriented programming ● Everything you manipulate is an object ● And the results of the manipulation is an object ● e.g. The number 4,if used, is an object Irb> 4.class Python : len() Fixnum Ruby: obj.length
  • 3. Setting up and installing ruby ● There are various ways of installing ruby ● RailsInstaller for windows and osx (http://railsinstaller.org) ● Compiling from source ● Using a package manager like rvm..most popular
  • 4. Ruby version manager(rvm) ● In the ruby world, rvm is the most popular method to install ruby and rails ● Rvm is only available for mac os x,linux and unix ● Rvm allows you to work with multiple versions of ruby ● To install rvm you need to have the curl program installed
  • 5. Installing rvm(linux) $ sudo apt-get install curl $ curl -L https://get.rvm.io | bash -s stable –ruby $ rvm requirements $ rvm install 1.9.3
  • 6. Standard types - numbers ● Numbers ● Ruby supports integers and floating point numbers ● Integers within a certain range (normally -230 to 230-1 or -262 to 262-1) are held internally in binary form, and are objects of class Fixnum ● Integers outside the above range are stored in objects of class Bignum ● Ruby automatically manages the conversion of Fixnum to Bignum and vice versa ● Integers in ruby support several types of iterators
  • 7. Standard types- numbers ● e.g. Of iterators ● 3.times { print "X " } ● 1.upto(5) { |i| print i, " " } ● 99.downto(95) { |i| print i, " " } ● 50.step(80, 5) { |i| print i, " " }
  • 8. Standard types - strings ● Strings in ruby are simply a sequence of 8-bit bytes ● In ruby strings can be assigned using either a double quotes or a single quote ● a_string1 = 'hello world' ● a_string2 = “hello world” ● The difference comes ● when you want to use a special character e.g. An apostrophe ● a_string1 = “Binn's world” ● a_string2 = 'Binn's world' # you need to use an escape sequence here
  • 9. Standard types - string ● Single quoted strings only supports 2 escape sequences, viz. ● ' - single quote ● - single backslash ● Double quotes allows for many more escape sequences ● They also allow you to embed variables or ruby code commonly called as interpolation puts "Enter name" name = gets.chomp puts "Your name is #{name}"
  • 10. Standard types - string Common escape sequences available are : ● " – double quote ● – single backslash ● a – bell/alert ● b – backspace ● r – carriage return ● n – newline ● s – space ● t – tab ●
  • 11. Working with strings gsub Returns a copy of str with str.gsub( pattern, all occurrences of pattern replacement ) replaced with either replacement or the value of the block. chomp Returns a new String with str.chomp the given record separator removed from the end of str (if present). count Return the count of str.count characters inside string strip Removes leading and str.strip trailing spaces from a string to_i Converts the string to a str.to_i number(Fixnum) upcase Upcases the content of the str.upcase strings http://www.ruby-doc.org/core-1.9.3/String.html#method-i-strip
  • 12. Standard types - ranges ● A Range represents an interval—a set of values with a start and an end ● In ruby, Ranges may be constructed using the s..e and s...e literals, or with Range::new ● ('a'..'e').to_a #=> ["a", "b", "c", "d", "e"] ● ('a'...'e').to_a #=> ["a", "b", "c", "d"]
  • 13. Using ranges ● Comparison ● (0..2) == (0..2) #=> true ● (0..2) == Range.new(0,2) #=> true ● (0..2) == (0...2) #=> false
  • 14. Using ranges ● Using in iteration (10..15).each do |n| print n, ' ' end
  • 15. Using ranges ● Checking for members ● ("a".."z").include?("g") # -> true ● ("a".."z").include?("A") # -> false
  • 16. Methods ● Methods are defined using the def keyword ● By convention methods that act as a query are often named in ruby with a trailing '?' ● e.g. str.instance_of? ● Methods that might be dangerous(causing an exception e.g.) or modify the reciever are named with a trailing '!' ● e.g. user.save! ● '?' and '!' are the only 2 special characters allowed in method name
  • 17. Defining methods ● Simple method: def mymethod end ● Methods with arguments: def mymethod2(arg1, arg2) end ● Methods with variable length arguments def varargs(arg1, *rest) "Got #{arg1} and #{rest.join(', ')}" end
  • 18. Methods ● In ruby, the last line of the method statement is returned back and there is no need to explicitly use a return statement def get_message(name) “hello, #{name}” end .Calling a method : get_message(“bin”) ● Calling a method without arguments : mymethod #calls the method
  • 19. Methods with blocks ● When a method is called, it can be given a random set of code to be executed called as blocks def takeBlock(p1) if block_given? yield(p1) else p1 end end
  • 20. Calling methods with blocks takeBlock("no block") #no block provided takeBlock("no block") { |s| s.sub(/no /, '') }
  • 21. Classes ● Classes in ruby are defined by using the keyword 'class' ● By convention, ruby demands that the class name should be capital ● An initialize method inside a class acts as a constructor ● An instance variable can be created using @
  • 22. class SimpleClass end //instantiate an object s1 = SimpleClass.new class Book def intitialize(title,author) @title = title @author = author end end //creating an object of the class b1 = Book.new("programming ruby","David")
  • 23. Making an attribute accessible ● Like in any other object oriented programming language, you will need to manipulate the attributes ● Ruby makes this easy with the keyword 'attr_reader' and 'attr_writer' ● This defines the getter and the setter methods for the attributes
  • 24. class Book attr_reader :title, :author def initialize(title,author) @title = title @author = author end end #using getters CompBook = Book.new(“A book”, “me”) Puts CompBook.title
  • 25. Symbols ● In ruby symbols can be declared using ':' ● e.g :name ● Symbols are a kind of strings ● The important difference is that they are immutable unlike strings ● Mutable objects can be changed after assignment while immutable objects can only be overwritten. ● puts "hello" << " world" ● puts :hello << :" world"
  • 26. Making an attribute writeable class Book attr_writer :title, :author def initialize(title,author) @title = title @author = author end end myBook = Book.new("A book", "author") myBook.title = "Some book"
  • 27. Class variables ● Sometimes you might need to declare a class variable in your class definition ● Class variables have a single copy for all the class objects ● In ruby, you can define a class variable using @@ symbol ● Class variables are private to the class so in order to access them outside the class you need to defined a getter or a class method
  • 28. Class Methods ● Class methods are defined using the keyword self ● e.g. – def self. myclass_method end
  • 29. Example class SomeClass @@instance = 0 #private attr_reader :instance def initialize @@instance += 1 end def self.instances @@instance end end s1 = SomeClass.new s2 = SomeClass.new puts "total instances #{SomeClass.instances}"
  • 30. Access Control ● You can specify 3 types of access control in ruby ● Private ● Protected ● Public ● By default, unless specified, all methods are public
  • 31. Access Control-Example class Program def get_sum calculate_internal end private def calculate_internal end end