SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado (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...
 

Similar a 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
 

Similar a 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
 

Más 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
 

Más 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
 

Último

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Último (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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