SlideShare a Scribd company logo
1 of 12
Download to read offline
Generated by Foxit PDF Creator © Foxit Software
                                         http://www.foxitsoftware.com For evaluation only.




                                Basic Programming in Ruby

Today’s Topics: [whirlwind overview]
• Introduction
• Fundamental Ruby data types, “operators”, methods
• Outputting text
     • print, puts, inspect
• Flow control
     • loops & iterators
     • conditionals
• Basic I/O
     • standard streams & file streams
     • reading & writing
• Intro to regular expression syntax
     • matching
     • substituting
• Writing custom methods (& classes)
Generated by Foxit PDF Creator © Foxit Software
                                                        http://www.foxitsoftware.com For evaluation only.




                                            Ruby Data Types

Ruby has essentially one data type: Objects that respond to messages (“methods”)
    • all data is an Object
    • variables are named locations that store Objects.
Let’s consider the classical “primitive” data types:
    • Numeric: Fixnum (42) and Float (42.42, 4.242e1)

    • Boolean: true and false
         • logically: nil & false are treated as “false”, all other objects are considered “true”

    • String (text)
         • interpolated: “t#{52.2 * 45}n”Hi Mom””
         • non-interpolatedt#{5*7}’
    • Range
         • end-inclusive, a.k.a. “fully closed range”: 2..19
         • right-end-exclusive, a.k.a. “half-open”: 2…19
Generated by Foxit PDF Creator © Foxit Software
                                                     http://www.foxitsoftware.com For evaluation only.




                      Ruby Data Types, “operators”, Methods

Key/special variables (predefined, part of language) :
    • nil (the no-Object; NULL, undef, none)
          • technically an instance (object) of the class NilClass

    • self (the current Object ; important later)


What about the standard bunch of operators?
    • sure, but keep in mind these are all actually methods
    • +, -, *, /, **
    • <, >, <=, >=, ==, !=, <=>
    • nil?()
    • Other important methods many objects respond to:
          • to_s() ; to_i() ; to_f() ; size() ; empty?()
          • reverse() ; reverse! ; include? ; is_a?
Generated by Foxit PDF Creator © Foxit Software
                                                             http://www.foxitsoftware.com For evaluation only.




                       More Complex, But Standard Data Types

Arrays
    • anArr = Array.new() ; anArr = []
    • 0-based indexes to access items in an Array using [] method à anArr[2] = “glycine” ; aA = anArr[2]
    • objects of different classes can be stored within the Array
    • responds to push(), pop(), shift(), unshift() methods
          • for adding & removing things from the end or the front of Arrays
    • Array merging and subtraction via + and –
    • Deleting items from Arrays via delete() & delete_at()
    • Looking for items via include?
          • slow for huge arrays obviously, or if we use repeatedly on moderate sized ones

Hashes
    • Look up items based on a key ß fast lookup
    • aHash = Hash.new() ; aHash = {} ; aHash = Hash.new {|hh,kk| hh[kk] = [] }
    • key-based access to items using [] method à aHash[“pros1”] = “chr14” ; chrom = aHash[“pros1”]
    • key can be any object, as can the stored value
    • check if there is already something within the array: key?(“pros2”)
    • number of items stored: size()
Generated by Foxit PDF Creator © Foxit Software
                                                               http://www.foxitsoftware.com For evaluation only.




                                                   Flow control: loops

Loops:
     • boringly simple and often not what you need
     • loop { }
     • while()
     • break keyword to end loop prematurely

Iteration:
     • more useful…very common to want to iterate over a set of things
     • iterator methods take blocks…a piece of code the iterator will call at each iteration, passing the
     current item to your piece of code
             • like a function pointer in C, function name callback in Javascript, anonymous methods in Java, etc

     • times {} ; upto {}
     • each {} ; each_key {}
     • each {} probably the most useful… Arrays, Strings, File (IO), so many Classes support it
     • look for specialty each_XXX {} methods like: each_byte{}, each_index {}, etc


Result: no need for weird constructs like for(ii=0; ii<arr.size;ii++) nor foreach…in… nor do-while
Generated by Foxit PDF Creator © Foxit Software
                                                          http://www.foxitsoftware.com For evaluation only.




                                        Flow control: conditionals

Conditional Expressions:
     • evaluate to true or to false
     • usually involve a simple method call or a comparison
          • nil? ; empty? ; include?
          • == ; != ; > ; <= ; … etc…
     • combine conditional expressions with boolean logic operators: or , and , || , &&, !, not
     • remember: only nil and false evaluate to false, all other objects are true
          • 0, “0”, “” evaluate to true (unlike in some other languages where they double as false values)



Use conditionals for flow control:
     • while() …   end

     • if() … elsif() … else … end
     • unless() … else … end
     • single line if() and unless()
     • Read about case statements, Ruby’s switch statement (a special form of if-elsif-else statements)
Generated by Foxit PDF Creator © Foxit Software
                                                               http://www.foxitsoftware.com For evaluation only.




                                       Basic I/O: Standard Streams

Reading & Writing: let’s discuss the 3 standard I/O streams first:


Generally, 3 standard streams available to all programs: stdout, stderr, stdin
     • most often, stdoutàscreen, stderràscreen, stdinßdata redirected into program
            • stdout and stderr sometimes redirected to files when running programs
     • in Ruby, these I/O streams explicitly available via $stdout, $stderr, $stdin
     • puts() ends up doing a $stdout.puts()
     • explicit $stderr.puts() calls can be useful for debugging, program progress updates, etc

Reading:
     • each {} ; each_line{} ß most useful (iteration again)
     • readline()

Writing:
     • we’ve been writing via puts(),       print() already…these Object methods write to the standard output
     IO stream e.g. $stdout.puts()
Generated by Foxit PDF Creator © Foxit Software
                                                           http://www.foxitsoftware.com For evaluation only.




                                     Basic I/O: Working With Files
File Objects:
     • open for reading à file = File.open(fileName)
     • open for writing à file = File.open(fileName, “w”) ßcreates a new file or wipes existing file out
     • open for appending à file = File.open(fileName, “a+”)
     • read() ; readline() ; each {} ; each_line {}
     • print() ; puts()
     • seek() ; rewind() ; pos()
Strings as IO:
     • what if we have some big String in memory and want to treat it as we would a File?
     • require ‘stringio’
     • strio = StringIO.new(str)
     • go crazy and use file methods mentioned above
     • newStr = strio.string() ß covert to regular String object
Interactive Programs:
     • generally avoid…when working with and producing big data files, you want to write things that can run
     without manual intervention
     • unless you are writing permanent tools for non-programmers to use (then also consider a GUI)
     • getc() ; gets() ; et alia
Generated by Foxit PDF Creator © Foxit Software
                                                          http://www.foxitsoftware.com For evaluation only.




                                      Regular Expressions Intro
Regular Expressions are like powerful patterns, applied against Strings
Very useful for dealing with text data!
Ruby’s regular expression syntax is like that of Perl, more or less. Also there is a pure object-
oriented syntax for more complex scenarios or for Java programmers to feel happy about.
Key pattern matching constructs:
     • . ß must match a single character
     • + ß must match one or more characters [ + is ‘one or more of preceding’ ]
     • * ß 0 or more characters match here [ * is ‘zero or more of preceding’ ]
     • ? ß 0 or 1 characters match here [ ? is ‘preceding may or may not be present’ ]
     • [;_-] ß match 1 of ; or _ or – (in this example)
     • [^;_-] ß match any 1 character except ; or _ or – (in this example)
     • [^;_-]+ ß match 1 or more of any character but ; or _ or – here
     • ^ ß match must start at beginning of a line [ $ anchors the end of a line ]
     • A ß match must start at beginning of whole string [ Z anchors at end of string ]
     • d ß match a digit [ D match any non-digit ]
     • w ß match a word character [ W match any non-word character ] [ word is alpha-num and _ ]
     • s ß match a whitespace character [ S match any non-whitespace character ]
     • foo|bar ß match foo or bar [ ‘match preceding or the following’ ]
Generated by Foxit PDF Creator © Foxit Software
                                                         http://www.foxitsoftware.com For evaluation only.




                                       Regular Expressions Intro
Backreferences:
     • () around any part of pattern will be captured for you to use later
     • /accNum=([^;]+)/
     • The text matched by each () is captured in a variable named $1, $2, $3, etc
     • If the pattern failed to match the string, then your backreference variable will have nil

Syntax: (apply regex against a variable storing a String object)
     • aString =~ /some([a-zA-z]+$/ ß returns index where matches or nil (nil is false…)
     • aString !~ /some([a-zA-z]+$/ ß assert String doesn’t match; returns true or false

Uses:
     • In conditionals [ if(line =~ /gene|exon/) then geneCount += 1 ; end ]
     • In String parsing
     • In String alteration (like s///g operation in Perl or sed)
           • gsub() ; gsub!()

Special Note:
     • Perl folks: where is tr/// ?
     • Right here: newStr = oldStr.tr(“aeiou”, “UOIEA”)
Generated by Foxit PDF Creator © Foxit Software
                                              http://www.foxitsoftware.com For evaluation only.




                       Writing and Running Ruby Programs
Begin your Ruby code file with this line (in Unix/Linux/OSX command line):
    #!/usr/bin/env ruby

Save your Ruby code file with “.rb” extension
Run your Ruby program like this on the command line:
    ruby <yourRubyFile.rb>

Or make file executable (Unix/Linux/OSX) via chmod +x <yourRubyFile.rb> then:
    ./<yourRubyFile.rb>


Comment your Ruby code using “#” character
    • Everything after the # is a comment and is ignored


Download and install Ruby here:
    http://www.ruby-lang.org
Generated by Foxit PDF Creator © Foxit Software
                                                             http://www.foxitsoftware.com For evaluation only.




                                    Basic Programming in Ruby

More Help:
1.   Try Ruby http://tryruby.hobix.com/
2.   Learning Ruby http://www.math.umd.edu/~dcarrera/ruby/0.3/
3.   Ruby Basic Tutorial http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm
4.   RubyLearning.com http://rubylearning.com/
5.   Ruby-Doc.org http://www.ruby-doc.org/
     •    Useful for looking up built-in classes & methods
     •    E.g. In Google: “rubydoc String”

6.   Ruby for Perl Programmers http://migo.sixbit.org/papers/Introduction_to_Ruby/slide-index.html

More Related Content

What's hot

What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...
What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...
What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...gagravarr
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)Erik Hatcher
 
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) David Fombella Pombal
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)Cloudera, Inc.
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8Garth Gilmour
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr DevelopersErik Hatcher
 
Towards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesTowards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesJose Emilio Labra Gayo
 
Json Rpc Proxy Generation With Php
Json Rpc Proxy Generation With PhpJson Rpc Proxy Generation With Php
Json Rpc Proxy Generation With Phpthinkphp
 
Neural Architectures for Named Entity Recognition
Neural Architectures for Named Entity RecognitionNeural Architectures for Named Entity Recognition
Neural Architectures for Named Entity RecognitionRrubaa Panchendrarajan
 

What's hot (19)

What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...
What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...
What's With The 1S And 0S? Making Sense Of Binary Data At Scale With Tika And...
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
 
ShEx vs SHACL
ShEx vs SHACLShEx vs SHACL
ShEx vs SHACL
 
SHACL by example
SHACL by exampleSHACL by example
SHACL by example
 
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
ShEx by Example
ShEx by ExampleShEx by Example
ShEx by Example
 
Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)
 
RDF validation tutorial
RDF validation tutorialRDF validation tutorial
RDF validation tutorial
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
Swift Basics
Swift BasicsSwift Basics
Swift Basics
 
Data shapes-test-suite
Data shapes-test-suiteData shapes-test-suite
Data shapes-test-suite
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Towards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression DerivativesTowards an RDF Validation Language based on Regular Expression Derivatives
Towards an RDF Validation Language based on Regular Expression Derivatives
 
Json Rpc Proxy Generation With Php
Json Rpc Proxy Generation With PhpJson Rpc Proxy Generation With Php
Json Rpc Proxy Generation With Php
 
Neural Architectures for Named Entity Recognition
Neural Architectures for Named Entity RecognitionNeural Architectures for Named Entity Recognition
Neural Architectures for Named Entity Recognition
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 

Viewers also liked

L E A R N I N G, T E A C H I N G A N D S U P E R L I V I N G D R
L E A R N I N G,  T E A C H I N G  A N D  S U P E R L I V I N G  D RL E A R N I N G,  T E A C H I N G  A N D  S U P E R L I V I N G  D R
L E A R N I N G, T E A C H I N G A N D S U P E R L I V I N G D Rdrsolapurkar
 
php-and-zend-framework-getting-started
php-and-zend-framework-getting-startedphp-and-zend-framework-getting-started
php-and-zend-framework-getting-startedtutorialsruby
 
CSS-Tutorial-boxmodel
CSS-Tutorial-boxmodelCSS-Tutorial-boxmodel
CSS-Tutorial-boxmodeltutorialsruby
 
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
 
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
 

Viewers also liked (7)

L E A R N I N G, T E A C H I N G A N D S U P E R L I V I N G D R
L E A R N I N G,  T E A C H I N G  A N D  S U P E R L I V I N G  D RL E A R N I N G,  T E A C H I N G  A N D  S U P E R L I V I N G  D R
L E A R N I N G, T E A C H I N G A N D S U P E R L I V I N G D R
 
psager
psagerpsager
psager
 
php-and-zend-framework-getting-started
php-and-zend-framework-getting-startedphp-and-zend-framework-getting-started
php-and-zend-framework-getting-started
 
d_ltr_print
d_ltr_printd_ltr_print
d_ltr_print
 
CSS-Tutorial-boxmodel
CSS-Tutorial-boxmodelCSS-Tutorial-boxmodel
CSS-Tutorial-boxmodel
 
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>
 
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>
 

Similar to Ruby1_full (20)

MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
05php
05php05php
05php
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
05php
05php05php
05php
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
The Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneThe Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhone
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Erlang/OTP for Rubyists
Erlang/OTP for RubyistsErlang/OTP for Rubyists
Erlang/OTP for Rubyists
 
Python assignment help
Python assignment helpPython assignment help
Python assignment help
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 

More from 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
 
&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
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascripttutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascripttutorialsruby
 

More from 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" />
 
&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
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 

Recently uploaded

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 

Recently uploaded (20)

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 

Ruby1_full

  • 1. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Basic Programming in Ruby Today’s Topics: [whirlwind overview] • Introduction • Fundamental Ruby data types, “operators”, methods • Outputting text • print, puts, inspect • Flow control • loops & iterators • conditionals • Basic I/O • standard streams & file streams • reading & writing • Intro to regular expression syntax • matching • substituting • Writing custom methods (& classes)
  • 2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Ruby Data Types Ruby has essentially one data type: Objects that respond to messages (“methods”) • all data is an Object • variables are named locations that store Objects. Let’s consider the classical “primitive” data types: • Numeric: Fixnum (42) and Float (42.42, 4.242e1) • Boolean: true and false • logically: nil & false are treated as “false”, all other objects are considered “true” • String (text) • interpolated: “t#{52.2 * 45}n”Hi Mom”” • non-interpolatedt#{5*7}’ • Range • end-inclusive, a.k.a. “fully closed range”: 2..19 • right-end-exclusive, a.k.a. “half-open”: 2…19
  • 3. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Ruby Data Types, “operators”, Methods Key/special variables (predefined, part of language) : • nil (the no-Object; NULL, undef, none) • technically an instance (object) of the class NilClass • self (the current Object ; important later) What about the standard bunch of operators? • sure, but keep in mind these are all actually methods • +, -, *, /, ** • <, >, <=, >=, ==, !=, <=> • nil?() • Other important methods many objects respond to: • to_s() ; to_i() ; to_f() ; size() ; empty?() • reverse() ; reverse! ; include? ; is_a?
  • 4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. More Complex, But Standard Data Types Arrays • anArr = Array.new() ; anArr = [] • 0-based indexes to access items in an Array using [] method à anArr[2] = “glycine” ; aA = anArr[2] • objects of different classes can be stored within the Array • responds to push(), pop(), shift(), unshift() methods • for adding & removing things from the end or the front of Arrays • Array merging and subtraction via + and – • Deleting items from Arrays via delete() & delete_at() • Looking for items via include? • slow for huge arrays obviously, or if we use repeatedly on moderate sized ones Hashes • Look up items based on a key ß fast lookup • aHash = Hash.new() ; aHash = {} ; aHash = Hash.new {|hh,kk| hh[kk] = [] } • key-based access to items using [] method à aHash[“pros1”] = “chr14” ; chrom = aHash[“pros1”] • key can be any object, as can the stored value • check if there is already something within the array: key?(“pros2”) • number of items stored: size()
  • 5. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Flow control: loops Loops: • boringly simple and often not what you need • loop { } • while() • break keyword to end loop prematurely Iteration: • more useful…very common to want to iterate over a set of things • iterator methods take blocks…a piece of code the iterator will call at each iteration, passing the current item to your piece of code • like a function pointer in C, function name callback in Javascript, anonymous methods in Java, etc • times {} ; upto {} • each {} ; each_key {} • each {} probably the most useful… Arrays, Strings, File (IO), so many Classes support it • look for specialty each_XXX {} methods like: each_byte{}, each_index {}, etc Result: no need for weird constructs like for(ii=0; ii<arr.size;ii++) nor foreach…in… nor do-while
  • 6. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Flow control: conditionals Conditional Expressions: • evaluate to true or to false • usually involve a simple method call or a comparison • nil? ; empty? ; include? • == ; != ; > ; <= ; … etc… • combine conditional expressions with boolean logic operators: or , and , || , &&, !, not • remember: only nil and false evaluate to false, all other objects are true • 0, “0”, “” evaluate to true (unlike in some other languages where they double as false values) Use conditionals for flow control: • while() … end • if() … elsif() … else … end • unless() … else … end • single line if() and unless() • Read about case statements, Ruby’s switch statement (a special form of if-elsif-else statements)
  • 7. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Basic I/O: Standard Streams Reading & Writing: let’s discuss the 3 standard I/O streams first: Generally, 3 standard streams available to all programs: stdout, stderr, stdin • most often, stdoutàscreen, stderràscreen, stdinßdata redirected into program • stdout and stderr sometimes redirected to files when running programs • in Ruby, these I/O streams explicitly available via $stdout, $stderr, $stdin • puts() ends up doing a $stdout.puts() • explicit $stderr.puts() calls can be useful for debugging, program progress updates, etc Reading: • each {} ; each_line{} ß most useful (iteration again) • readline() Writing: • we’ve been writing via puts(), print() already…these Object methods write to the standard output IO stream e.g. $stdout.puts()
  • 8. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Basic I/O: Working With Files File Objects: • open for reading à file = File.open(fileName) • open for writing à file = File.open(fileName, “w”) ßcreates a new file or wipes existing file out • open for appending à file = File.open(fileName, “a+”) • read() ; readline() ; each {} ; each_line {} • print() ; puts() • seek() ; rewind() ; pos() Strings as IO: • what if we have some big String in memory and want to treat it as we would a File? • require ‘stringio’ • strio = StringIO.new(str) • go crazy and use file methods mentioned above • newStr = strio.string() ß covert to regular String object Interactive Programs: • generally avoid…when working with and producing big data files, you want to write things that can run without manual intervention • unless you are writing permanent tools for non-programmers to use (then also consider a GUI) • getc() ; gets() ; et alia
  • 9. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Regular Expressions Intro Regular Expressions are like powerful patterns, applied against Strings Very useful for dealing with text data! Ruby’s regular expression syntax is like that of Perl, more or less. Also there is a pure object- oriented syntax for more complex scenarios or for Java programmers to feel happy about. Key pattern matching constructs: • . ß must match a single character • + ß must match one or more characters [ + is ‘one or more of preceding’ ] • * ß 0 or more characters match here [ * is ‘zero or more of preceding’ ] • ? ß 0 or 1 characters match here [ ? is ‘preceding may or may not be present’ ] • [;_-] ß match 1 of ; or _ or – (in this example) • [^;_-] ß match any 1 character except ; or _ or – (in this example) • [^;_-]+ ß match 1 or more of any character but ; or _ or – here • ^ ß match must start at beginning of a line [ $ anchors the end of a line ] • A ß match must start at beginning of whole string [ Z anchors at end of string ] • d ß match a digit [ D match any non-digit ] • w ß match a word character [ W match any non-word character ] [ word is alpha-num and _ ] • s ß match a whitespace character [ S match any non-whitespace character ] • foo|bar ß match foo or bar [ ‘match preceding or the following’ ]
  • 10. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Regular Expressions Intro Backreferences: • () around any part of pattern will be captured for you to use later • /accNum=([^;]+)/ • The text matched by each () is captured in a variable named $1, $2, $3, etc • If the pattern failed to match the string, then your backreference variable will have nil Syntax: (apply regex against a variable storing a String object) • aString =~ /some([a-zA-z]+$/ ß returns index where matches or nil (nil is false…) • aString !~ /some([a-zA-z]+$/ ß assert String doesn’t match; returns true or false Uses: • In conditionals [ if(line =~ /gene|exon/) then geneCount += 1 ; end ] • In String parsing • In String alteration (like s///g operation in Perl or sed) • gsub() ; gsub!() Special Note: • Perl folks: where is tr/// ? • Right here: newStr = oldStr.tr(“aeiou”, “UOIEA”)
  • 11. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Writing and Running Ruby Programs Begin your Ruby code file with this line (in Unix/Linux/OSX command line): #!/usr/bin/env ruby Save your Ruby code file with “.rb” extension Run your Ruby program like this on the command line: ruby <yourRubyFile.rb> Or make file executable (Unix/Linux/OSX) via chmod +x <yourRubyFile.rb> then: ./<yourRubyFile.rb> Comment your Ruby code using “#” character • Everything after the # is a comment and is ignored Download and install Ruby here: http://www.ruby-lang.org
  • 12. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Basic Programming in Ruby More Help: 1. Try Ruby http://tryruby.hobix.com/ 2. Learning Ruby http://www.math.umd.edu/~dcarrera/ruby/0.3/ 3. Ruby Basic Tutorial http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm 4. RubyLearning.com http://rubylearning.com/ 5. Ruby-Doc.org http://www.ruby-doc.org/ • Useful for looking up built-in classes & methods • E.g. In Google: “rubydoc String” 6. Ruby for Perl Programmers http://migo.sixbit.org/papers/Introduction_to_Ruby/slide-index.html