SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
Ruby
       A quick Ruby Tutorial
                                          •   Invented by Yukihiro Matsumoto, “Matz”
                                          •   1995
                                          •   Fully object-oriented
               COMP313
Source: Programming Ruby, The Pragmatic   •   alternative to Perl or Python
Programmers’ Guide by Dave Thomas, Chad
          Fowler, and Andy Hunt




                How to run                      Simple method example
 • Command line: ruby <file>              def sum (n1, n2)
                                            n1 + n2
 • Interactive: irb
                                          end

 • Resources:                             sum( 3 , 4) => 7
   – see web page                         sum(“cat”, “dog”) => “catdog”
   – man ruby
                                          load “fact.rb”
                                          fact(10) => 3628800




       executable shell script                         Method calls
 #!/usr/bin/ruby                          "gin joint".length   9
 print “hello worldn”                     "Rick".index("c")   2
                                          -1942.abs       1942
 or better: #!/usr/bin/env ruby
 make file executable: chmod +x file.rb   Strings: ‘asn’ => “asn”
                                          x=3
                                          y = “x is #{x}” => “x is 3”




                                                                                       1
Another method definition                         Name conventions/rules
def say_goodnight(name)                           • local var: start with lowercase or _
  "Good night, #{name}"                           • global var: start with $
end                                               • instance var: start with @
puts say_goodnight('Ma')                          • class var: start with @@
                                                  • class names, constant: start uppercase
                                                  following: any letter/digit/_ multiwords
produces: Good night, Ma                            either _ (instance) or mixed case
                                                    (class), methods may end in ?,!,=




          Naming examples                                  Arrays and Hashes
•   local: name, fish_and_chips, _26              • indexed collections, grow as needed
•   global: $debug, $_, $plan9                    • array: index/key is 0-based integer
                                                  • hash: index/key is any object
•   instance: @name, @point_1
                                                  a = [ 1, 2, “3”, “hello”]
•   class: @@total, @@SINGLE,
                                                  a[0] => 1                      a[2] => “3”
•   constant/class: PI, MyClass,                  a[5] => nil (ala null in Java, but proper Object)
    FeetPerMile
                                                  a[6] = 1
                                                  a => [1, 2, “3”, “hello”, nil, nil, 1]




            Hash examples                                  Control: if example
inst = { “a” => 1, “b” => 2 }                     if count > 10
inst[“a”] => 1                                      puts "Try again"
inst[“c”] => nil
                                                  elsif tries == 3
inst = Hash.new(0) #explicit new with default 0
  instead of nil for empty slots                    puts "You lose"
inst[“a”] => 0                                    else
inst[“a”] += 1                                      puts "Enter a number"
inst[“a”] => 1                                    end




                                                                                                      2
Control: while example                                                 nil is treated as false
while weight < 100 and num_pallets <= 30                            while line = gets
 pallet = next_pallet()                                              puts line.downcase
 weight += pallet.weight                                            end
 num_pallets += 1
end




                                                                         builtin support for Regular
            Statement modifiers
                                                                                 expressions
 • useful for single statement if or while                          /Perl|Python/ matches Perl or Python
 • similar to Perl                                                  /ab*c/ matches one a, zero or more bs and
                                                                       one c
 • statement followed by condition:
                                                                    /ab+c/ matches one a, one or more bs and one
                                                                       c
 puts "Danger" if radiation > 3000                                  /s/ matches any white space
                                                                    /d/ matches any digit
 square = 2                                                         /w/ characters in typical words
 square = square*square while square < 1000                         /./ any character
                                                                    (more later)




                more on regexps                                               Code blocks and yield
 if line =~ /Perl|Python/                                           def call_block
   puts "Scripting language mentioned: #{line}"                      puts "Start of method"
 end                                                                 yield
                                                                     yield
                                                                     puts "End of method"
 line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'
                                                                    end
 line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby’

                                                                    call_block { puts "In the block" }   produces:
 # replace all occurances of both ‘Perl’ and ‘Python’ with ‘Ruby’   Start of method
 line.gsub(/Perl|Python/, 'Ruby')                                   In the block
                                                                    In the block
                                                                    End of method




                                                                                                                     3
parameters for yield                           Code blocks for iteration
def call_block                                    animals = %w( ant bee cat dog elk ) # create an array
 yield("hello",2)                                  # shortcut for animals = {“ant”,”bee”,”cat”,”dog”,”elk”}
end                                               animals.each {|animal| puts animal } # iterate
                                                           produces:
then                                              ant
                                                  bee
                                                  cat
call_block { | s, n | puts s*n, "n" }   prints
                                                  dog
hellohello
                                                  elk




 Implement “each” with “yield”                                   More iterations
# within class Array...                           [ 'cat', 'dog', 'horse' ].each {|name| print name, "
                                                     "}
def each
                                                  5.times { print "*" }
 for every element # <-- not valid Ruby
                                                  3.upto(6) {|i| print i }
  yield(element)                                  ('a'..'e').each {|char| print char }
 end                                              [1,2,3].find { |x| x > 1}
end                                               (1...10).find_all { |x| x < 3}




                        I/O                       leaving the Perl legacy behind
• puts and print, and C-like printf:              while gets
printf("Number: %5.2f,nString: %sn", 1.23,       if /Ruby/
   "hello")                                          print
 #produces:                                        end
Number: 1.23,                                     end
String: hello
#input                                            ARGF.each {|line| print line if line =~ /Ruby/ }
line = gets
print line                                        print ARGF.grep(/Ruby/)




                                                                                                              4
Classes                                    override to_s
class Song                                        s.to_s => "#<Song:0x2282d0>"
 def initialize(name, artist, duration)
  @name = name                                    class Song
  @artist = artist                                 def to_s
  @duration = duration                               "Song: #@name--#@artist (#@duration)"
 end                                               end
end                                               end

song = Song.new("Bicylops", "Fleck", 260)         s.to_s => "Song: Bicylops--Fleck (260 )”




                 Some subclass                           supply to_s for subclass
class KaraokeSong < Song                          class KaraokeSong < Song
                                                   # Format as a string by appending lyrics to parent's to_s value.
 def initialize(name, artist, duration, lyrics)
                                                   def to_s
   super(name, artist, duration)                    super + " [#@lyrics]"
   @lyrics = lyrics                                end
 end                                              end

end                                               song.to_s    "Song: My Way--Sinatra (225) [And now, the...]"
song = KaraokeSong.new("My Way", "Sinatra",
  225, "And now, the...")
song.to_s       "Song: My Way--Sinatra (225)"




                       Accessors
class Song
 def name
   @name
 end
end
s.name => “My Way”

# simpler way to achieve the same
class Song
 attr_reader :name, :artist, :duration
end




                                                                                                                      5

Contenu connexe

Tendances

Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
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
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartConanandvns
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In ScalaJoey Gibson
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Wim Vanderbauwhede
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in ScalaKnoldus Inc.
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesWim Vanderbauwhede
 

Tendances (20)

Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Go &lt;-> Ruby
Go &lt;-> RubyGo &lt;-> Ruby
Go &lt;-> Ruby
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
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
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartCon
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in Scala
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 

En vedette (20)

11 19 Biogas
11 19 Biogas11 19 Biogas
11 19 Biogas
 
Done For You SEO SMO PowerPoint
Done For You SEO SMO PowerPoint   Done For You SEO SMO PowerPoint
Done For You SEO SMO PowerPoint
 
Not So Native
Not So NativeNot So Native
Not So Native
 
Plan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in CataloniaPlan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in Catalonia
 
Mecanismo
MecanismoMecanismo
Mecanismo
 
Avaliação da formação contínua
Avaliação da formação contínuaAvaliação da formação contínua
Avaliação da formação contínua
 
中国移动Boss3.0技术方案
中国移动Boss3.0技术方案中国移动Boss3.0技术方案
中国移动Boss3.0技术方案
 
Hypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas KashalikarHypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas Kashalikar
 
Christmas in Germany
Christmas in GermanyChristmas in Germany
Christmas in Germany
 
cgipmtut
cgipmtutcgipmtut
cgipmtut
 
Rf matematicas i
Rf matematicas iRf matematicas i
Rf matematicas i
 
Some shoe trends ´07
Some shoe trends ´07Some shoe trends ´07
Some shoe trends ´07
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Australia
AustraliaAustralia
Australia
 
Wapflow
WapflowWapflow
Wapflow
 
Che cosa è l'amore?
Che cosa è l'amore?Che cosa è l'amore?
Che cosa è l'amore?
 
Winter09TECH
Winter09TECHWinter09TECH
Winter09TECH
 
S T U D Y O F G I T A 4 T H F L O W E R D R
S T U D Y  O F  G I T A 4 T H  F L O W E R  D RS T U D Y  O F  G I T A 4 T H  F L O W E R  D R
S T U D Y O F G I T A 4 T H F L O W E R D R
 
由一个简单的程序谈起--之四
由一个简单的程序谈起--之四由一个简单的程序谈起--之四
由一个简单的程序谈起--之四
 
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
 

Similaire à ruby1_6up

Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2Rakesh Mukundan
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Andrea Telatin
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueJames Thompson
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1Brady Cheng
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlSway Wang
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 

Similaire à ruby1_6up (20)

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Dernier (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

ruby1_6up

  • 1. Ruby A quick Ruby Tutorial • Invented by Yukihiro Matsumoto, “Matz” • 1995 • Fully object-oriented COMP313 Source: Programming Ruby, The Pragmatic • alternative to Perl or Python Programmers’ Guide by Dave Thomas, Chad Fowler, and Andy Hunt How to run Simple method example • Command line: ruby <file> def sum (n1, n2) n1 + n2 • Interactive: irb end • Resources: sum( 3 , 4) => 7 – see web page sum(“cat”, “dog”) => “catdog” – man ruby load “fact.rb” fact(10) => 3628800 executable shell script Method calls #!/usr/bin/ruby "gin joint".length 9 print “hello worldn” "Rick".index("c") 2 -1942.abs 1942 or better: #!/usr/bin/env ruby make file executable: chmod +x file.rb Strings: ‘asn’ => “asn” x=3 y = “x is #{x}” => “x is 3” 1
  • 2. Another method definition Name conventions/rules def say_goodnight(name) • local var: start with lowercase or _ "Good night, #{name}" • global var: start with $ end • instance var: start with @ puts say_goodnight('Ma') • class var: start with @@ • class names, constant: start uppercase following: any letter/digit/_ multiwords produces: Good night, Ma either _ (instance) or mixed case (class), methods may end in ?,!,= Naming examples Arrays and Hashes • local: name, fish_and_chips, _26 • indexed collections, grow as needed • global: $debug, $_, $plan9 • array: index/key is 0-based integer • hash: index/key is any object • instance: @name, @point_1 a = [ 1, 2, “3”, “hello”] • class: @@total, @@SINGLE, a[0] => 1 a[2] => “3” • constant/class: PI, MyClass, a[5] => nil (ala null in Java, but proper Object) FeetPerMile a[6] = 1 a => [1, 2, “3”, “hello”, nil, nil, 1] Hash examples Control: if example inst = { “a” => 1, “b” => 2 } if count > 10 inst[“a”] => 1 puts "Try again" inst[“c”] => nil elsif tries == 3 inst = Hash.new(0) #explicit new with default 0 instead of nil for empty slots puts "You lose" inst[“a”] => 0 else inst[“a”] += 1 puts "Enter a number" inst[“a”] => 1 end 2
  • 3. Control: while example nil is treated as false while weight < 100 and num_pallets <= 30 while line = gets pallet = next_pallet() puts line.downcase weight += pallet.weight end num_pallets += 1 end builtin support for Regular Statement modifiers expressions • useful for single statement if or while /Perl|Python/ matches Perl or Python • similar to Perl /ab*c/ matches one a, zero or more bs and one c • statement followed by condition: /ab+c/ matches one a, one or more bs and one c puts "Danger" if radiation > 3000 /s/ matches any white space /d/ matches any digit square = 2 /w/ characters in typical words square = square*square while square < 1000 /./ any character (more later) more on regexps Code blocks and yield if line =~ /Perl|Python/ def call_block puts "Scripting language mentioned: #{line}" puts "Start of method" end yield yield puts "End of method" line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' end line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby’ call_block { puts "In the block" } produces: # replace all occurances of both ‘Perl’ and ‘Python’ with ‘Ruby’ Start of method line.gsub(/Perl|Python/, 'Ruby') In the block In the block End of method 3
  • 4. parameters for yield Code blocks for iteration def call_block animals = %w( ant bee cat dog elk ) # create an array yield("hello",2) # shortcut for animals = {“ant”,”bee”,”cat”,”dog”,”elk”} end animals.each {|animal| puts animal } # iterate produces: then ant bee cat call_block { | s, n | puts s*n, "n" } prints dog hellohello elk Implement “each” with “yield” More iterations # within class Array... [ 'cat', 'dog', 'horse' ].each {|name| print name, " "} def each 5.times { print "*" } for every element # <-- not valid Ruby 3.upto(6) {|i| print i } yield(element) ('a'..'e').each {|char| print char } end [1,2,3].find { |x| x > 1} end (1...10).find_all { |x| x < 3} I/O leaving the Perl legacy behind • puts and print, and C-like printf: while gets printf("Number: %5.2f,nString: %sn", 1.23, if /Ruby/ "hello") print #produces: end Number: 1.23, end String: hello #input ARGF.each {|line| print line if line =~ /Ruby/ } line = gets print line print ARGF.grep(/Ruby/) 4
  • 5. Classes override to_s class Song s.to_s => "#<Song:0x2282d0>" def initialize(name, artist, duration) @name = name class Song @artist = artist def to_s @duration = duration "Song: #@name--#@artist (#@duration)" end end end end song = Song.new("Bicylops", "Fleck", 260) s.to_s => "Song: Bicylops--Fleck (260 )” Some subclass supply to_s for subclass class KaraokeSong < Song class KaraokeSong < Song # Format as a string by appending lyrics to parent's to_s value. def initialize(name, artist, duration, lyrics) def to_s super(name, artist, duration) super + " [#@lyrics]" @lyrics = lyrics end end end end song.to_s "Song: My Way--Sinatra (225) [And now, the...]" song = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") song.to_s "Song: My Way--Sinatra (225)" Accessors class Song def name @name end end s.name => “My Way” # simpler way to achieve the same class Song attr_reader :name, :artist, :duration end 5