Ruby

120
Ruby

description

An introduction to Ruby.

Transcript of Ruby

Page 1: Ruby

Ruby

Page 2: Ruby

1. Taal

Page 3: Ruby

class  Application{    public  static  void  main(String[]  args)    {        System.out.println("Hello  World!");    }}

Page 4: Ruby

puts  "Hello  World!"

Page 5: Ruby

import  java.io.InputStreamReader;import  java.io.BufferedReader;

class  Application{        public  static  void  main(String[]  args)        {                System.out.println("What  is  your  name?");

               String  name  =  "";                InputStreamReader  input  =  new  InputStreamReader(System.in);                BufferedReader  reader  =  new  BufferedReader(input);                try                {                        name  =  reader.readLine().trim();                }                catch(Exception  e)  {  ;  }

               System.out.println("Nice  to  meet  you,  "  +  name  +  '!');        }}

Page 6: Ruby

puts  "What  is  your  name?"name  =  gets.chompputs  "Nice  to  meet  you,  #{name}!"

Page 7: Ruby

What  is  your  name?DenisNice  to  meet  you,  Denis!

Page 8: Ruby

String  name  =  new  LibraryFactory(AbstractFactoryFactoryWeight().getFactoryAbstractFactory().getFactoryFactory().getFactory().getAbstractSystem().getConsoleFactory().getConsolable().injectDependency(ReadingFactory().getReader())).getLineFactory().getLine().read();

Page 9: Ruby

* * *

Page 10: Ruby

#  dit  is  commentaar#  dit  is  meer  commentaarputs  'dit  is  geen  commentaar'

Page 11: Ruby

a  =  10

puts  'a  is  #{a}'puts  "a  is  #{a}"

#  output:#  a  is  #{a}#  a  is  10

Page 12: Ruby

amount  =  42

if  amount  ==  42    puts  "Perfect!"end

Page 13: Ruby

amount  =  42

puts  "Perfect!"  if  amount  ==  42

Page 14: Ruby

amount  =  42

if  amount  <  10    puts  "Not  enough"elsif  amount  <  50    puts  "Enough"else    puts  "Too  much"end

Page 15: Ruby

names  =  [  'Thomas',  'Dieter',  'Denis',                    'Ruben',  'Hendrik',  'Niels',                    'Wim',  'Wouter'  ]

for  name  in  names  do    puts  "Hello  #{name}"end

Page 16: Ruby

names  =  [  'Thomas',  'Dieter',  'Denis',                    'Ruben',  'Hendrik',  'Niels',                    'Wim',  'Wouter'  ]

names.each  do  |name|    puts  "Hello  #{name}"end

Page 17: Ruby

names  =  [  'Thomas',  'Dieter',  'Denis',                    'Ruben',  'Hendrik',  'Niels',                    'Wim',  'Wouter'  ]

names.sort.each  do  |name|    puts  "Hello  #{name}"end

Page 18: Ruby

(31..47).each  do  |i|    puts  iend

Page 19: Ruby

10.times  do    puts  "Hello"end

Page 20: Ruby

count  =  0while  gets    count  +=  1endputs  "Number  of  lines:  #{count}"

Page 21: Ruby

count  =  0

count  +=  1  while  gets

puts  "Number  of  lines:  #{count}"

Page 22: Ruby

def  print_welcome_message    puts  "Hello!"    puts  "I  am  a  function."end

print_welcome_message

Page 23: Ruby

def  fact(n)    if  n  ==  0        return  1    else        return  n  *  fact(n-­‐1)    endend

puts  fact(10)

Page 24: Ruby

def  fact(n)    if  n  ==  0        1    else        n  *  fact(n-­‐1)    endend

puts  fact(10)

Page 25: Ruby

def  fact(n)    if  n  ==  0        1    else        n  *  fact(n-­‐1)    endend

puts  fact(1000)

Page 26: Ruby

402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Page 27: Ruby

def  do_stuff    a  =  4    puts  "inside  the  function,  a  is  #{a}"end

a  =  1do_stuffputs  "outside  the  function,  a  is  #{a}"

#  output:#  inside  the  function,  a  is  4#  outside  the  function,  a  is  1

Page 28: Ruby

def  do_stuff    $a  =  4    puts  "inside  the  function,  $a  is  #{$a}"end

$a  =  1do_stuffputs  "outside  the  function,  $a  is  #{$a}"

#  output:#  inside  the  function,  $a  is  4#  outside  the  function,  $a  is  4

Page 29: Ruby

class  Person

   def  initialize(first_name,  last_name)        @first_name  =  first_name        @last_name    =  last_name    end

   def  get_first_name        @first_name    end

   def  get_last_name        @last_name    end

end

Page 30: Ruby

p  =  Person.new('Denis',  'Defreyne')puts  "I  am  #{p.get_first_name}."

Page 31: Ruby

class  Person

   def  initialize(first_name,  last_name)        @first_name  =  first_name        @last_name    =  last_name    end

   def  get_first_name        @first_name    end

   def  get_last_name        @last_name    end

end

Page 32: Ruby

class  Person

   attr_reader  :first_name,  :last_name

   def  initialize(first_name,  last_name)        @first_name  =  first_name        @last_name    =  last_name    end

end

Page 33: Ruby

p  =  Person.new('Denis',  'Defreyne')puts  "I  am  #{p.first_name}."

Page 34: Ruby

people  =  [    Person.new('Denis',      'Defreyne'),    Person.new('Wim',          'Vander  Schelden'),    Person.new('Dieter',    'De  Paepe'),    Person.new('Ruben',      'Verborgh'),    Person.new('Niels',      'Soetens'),    Person.new('Thomas',    'Spranghers'),    Person.new('Hendrik',  'Moens'),    Person.new('Wouter',    'Van  Isterdael')]

Page 35: Ruby

people.each  do  |person|    puts  "-­‐  #{person.first_name}"end

Page 36: Ruby

-­‐  Denis-­‐  Wim-­‐  Dieter-­‐  Ruben-­‐  Niels-­‐  Thomas-­‐  Hendrik-­‐  Wouter

Page 37: Ruby

some_people  =  people.select  do  |person|    person.first_name  =~  /^[A-­‐M]/end

some_people.each  do  |person|    puts  "-­‐  #{person.first_name}"end

Page 38: Ruby

-­‐  Denis-­‐  Dieter-­‐  Hendrik

Page 39: Ruby

first_names  =  people.map  do  |person|    person.first_nameend

first_names.each  do  |first_name|    puts  "-­‐  #{first_name}"end

Page 40: Ruby

-­‐  Denis-­‐  Wim-­‐  Dieter-­‐  Ruben-­‐  Niels-­‐  Thomas-­‐  Hendrik-­‐  Wouter

Page 41: Ruby

first_names  =  people.map  do  |person|    person.first_nameend

puts  first_names.join(',  ')

Page 42: Ruby

Denis,  Wim,  Dieter,  Ruben,  Niels,  Thomas,  Hendrik,  Wouter

Page 43: Ruby

i  =  0loop  do    puts  "#{i}..."    i  +=  1end

Page 44: Ruby

i  =  0while  i  <  100    puts  "#{i}..."    i  +=  1end

Page 45: Ruby

:symbol

'string'

Page 46: Ruby

wim  =  {    :first_name  =>  'Wim',    :last_name    =>  'Verschelden'}

puts  "Last  name:  #{wim[:last_name]}"

wim[:last_name]  =  'Vander  Schelden'puts  "Last  name:  #{wim[:last_name]}"

Page 47: Ruby

if  false    puts  "this  message  will  not  be  printed"end

Page 48: Ruby

if  nil    puts  "this  message  will  not  be  printed"end

Page 49: Ruby

if  0    puts  "this  message  will  be  printed"end

Page 50: Ruby

puts  "Lorem  ipsum  dolor  sit  amet..."puts("Lorem  ipsum  dolor  sit  amet...")

Page 51: Ruby

my_list  =  []

if  my_list.empty?    puts  "My  list  is  empty  :("end

Page 52: Ruby

my_list  =  [  'foo',  'bar',  'baz'  ]

if  my_list.include?('foo')    puts  "My  list  includes  'foo'."end

Page 53: Ruby

class  String    def  palindrome?        self.reverse  ==  self    endend

Page 54: Ruby

if  "straat".palindrome?    puts  "'straat'  is  een  palindroom."else    puts  "'straat'  is  geen  palindroom."end

Page 55: Ruby

words  =  [  'racecar',  'daad',  'straat',                    'koortsmeetsysteemstrook'  ]

palindromes  =  words.select  do  |w|    w.palindrome?end

palindromes.each  {  |p|  puts  p  }

Page 56: Ruby

filename  =  '/usr/share/dict/words'words  =  File.read(filename).split("\n")

palindromes  =  words.select  do  |w|    w.palindrome?  &&  w.size  >  5end

palindromes.each  {  |p|  puts  p  }

Page 57: Ruby

deedeeddeggedhallahkakkakmurdrumredderrepaperretterreviverrotatorsooloostebbetterret

Page 58: Ruby

email  =  '[email protected]'

puts  email.sub('@',  '  [AT]  ')#  denis.defreyne  [AT]  stoneship.org

puts  email#  [email protected]

Page 59: Ruby

email  =  '[email protected]'

email.sub!('@',  '  [AT]  ')puts  email#  denis.defreyne  [AT]  stoneship.org

Page 60: Ruby

module  PalindromeChecking    def  palindrome?        self.reverse  ==  self    endend

class  String    include  PalindromeCheckingend

class  Array    include  PalindromeCheckingend

Page 61: Ruby

puts  'racecar'.palindrome?#  true

puts  'straat'.palindrome?#  false

Page 62: Ruby

puts  [  1,  2,  4,  8,  4,  2,  1  ].palindrome?#  true

puts  [  1,  2,  3,  4,  5,  6,  7  ].palindrome?#  false

Page 63: Ruby

"asdf".blahblah

Page 64: Ruby

NoMethodError:  undefined  method  `blahblah'  for  "asdf":String   from  (irb):1

Page 65: Ruby

nil.reverse

Page 66: Ruby

NoMethodError:  undefined  method  `reverse'  for  nil:NilClass   from  (irb):2

Page 67: Ruby

nil.nil?#  true

Page 68: Ruby

begin    nil.reverserescue    puts  'tis  om  zeep  :('end

Page 69: Ruby

tis  om  zeep  :(

Page 70: Ruby

def  foobarize(s)    raise  ArgumentError.new('fail')  unless  s

   'foobar'end

foobarize(nil)

Page 71: Ruby

ArgumentError:  fail   from  (irb):8:in  `foobarize'   from  (irb):12   from  /usr/local/ruby/bin/irb:12:in  `<main>'

Page 72: Ruby

begin    foobarize(nil)rescue  ArgumentError  =>  e    puts  'tis  om  zeep  :('    puts  e.inspectend

Page 73: Ruby

tis  om  zeep  :(#<ArgumentError:  fail>

Page 74: Ruby

def  twice    yield    yieldend

twice  do    puts  "Hello  World"end

Page 75: Ruby

Hello  WorldHello  World

Page 76: Ruby

2. Testing

Page 77: Ruby

Unit Tests

Page 78: Ruby

class  ExampleTest  <  Test::Unit::TestCase

   def  test_bob        assert_equal('BOB',  'bob'.upcase)    end

end

Page 79: Ruby

▸  testrb  test.rb

Loaded  suite  test.rbStarted.Finished  in  0.000341  seconds.

1  tests,  1  assertions,  0  failures,  0  errors

Page 80: Ruby

class  ExampleTest  <  Test::Unit::TestCase

   def  test_bob        assert_equal('BOB',  'bob'.upcase)    end

   def  test_mike        assert_equal('BOB',  'mike'.upcase)    end

end

Page 81: Ruby

Loaded  suite  test.rbStarted.FFinished  in  0.029604  seconds.

   1)  Failure:test_mike(ExampleTest)  [test.rb:10]:<"BOB">  expected  but  was<"MIKE">.

2  tests,  2  assertions,  1  failures,  0  errors

Page 82: Ruby

▸  rake(in  ~/Documents/Development/nanoc/nanoc-­‐2.1.x)Loaded  suite  rake_test_loaderStarted........................................................................................................................................................................................................................................................................................................................................................Finished  in  9.425028  seconds.

344  tests,  1286  assertions,  0  failures,  0  errors

Page 83: Ruby

Mocks + Stubs

Page 84: Ruby

class  Person

   attr_accessor  :first_name,  :last_name

   def  initialize(first_name,  last_name)        @first_name  =  first_name        @last_name    =  last_name    end

end

Page 85: Ruby

class  PersonAnalyser

   def  initialize(person)        @person  =  person    end

   def  number_of_parts_in_last_name        @person.last_name.split(/\s+/).size    end

end

Page 86: Ruby

def  test_number_of_parts_in_last_name_with_one_part    person  =  Person.new('Denis',  'Defreyne')

   person_analyser  =  PersonAnalyser.new(person)

   assert_equal(1,        person_analyser.number_of_parts_in_last_name)end

Page 87: Ruby

def  test_number_of_parts_in_last_name_with_two_parts    person  =  Person.new('Wim',  'Vander  Schelden')

   person_analyser  =  PersonAnalyser.new(person)

   assert_equal(2,        person_analyser.number_of_parts_in_last_name)end

Page 88: Ruby

def  test_number_of_parts_in_last_name_with_one_part    person  =  mock    person.stubs(:first_name).returns('Denis')    person.stubs(:last_name).returns('Defreyne')

   person_analyser  =  PersonAnalyser.new(person)

   assert_equal(1,        person_analyser.number_of_parts_in_last_name)end

Page 89: Ruby

def  test_number_of_parts_in_last_name_with_two_parts    person  =  mock    person.stubs(:first_name).returns('Wim')    person.stubs(:last_name).returns('Vander  Schelden')

   person_analyser  =  PersonAnalyser.new(person)

   assert_equal(2,        person_analyser.number_of_parts_in_last_name)end

Page 90: Ruby

Loaded  suite  test.rbStarted....Finished  in  0.000934  seconds.

4  tests,  4  assertions,  0  failures,  0  errors

Page 91: Ruby

Specs

Page 92: Ruby

describe  'String'  do

   it  'must  be  able  to  reverse  a  string'  do        'bob'.reverse.must_equal  'bob'        'mike'.reverse.must_equal  'ekim'        'the  birds  sing  a  pretty  song'.reverse.must_equal            'gnos  ytterp  a  gnis  sdrib  eht'    end

end

Page 93: Ruby

it  'must  be  able  to  upcase  strings'  do   'bob'.upcase.must_equal  'BOB'   'mike'.upcase.must_equal  'MIKE'end

Page 94: Ruby

3. Tools

Page 95: Ruby

irb

Page 96: Ruby

▸  irb

irb(main):001:0>  "Hello".reverse=>  "olleH"irb(main):002:0>  "Test".upcase=>  "TEST"

Page 97: Ruby

nokogiri

Page 98: Ruby

require  'nokogiri'

url  =  'http://mystonline.com/'doc  =  Nokogiri::HTML(open(url))

links  =  doc.css('a')links.each  do  |link|    text  =  link.content    href  =  link.attributes['href']

   puts  "'#{text}'  links  to  #{href}."end

Page 99: Ruby

rubygems

Page 100: Ruby

▸  ruby  nokogiri-­‐test.rbtest.rb:1:in  `require':  no  such  file  to  load  -­‐-­‐  nokogiri  (LoadError)   from  test.rb:1

Page 101: Ruby

▸  sudo  gem  install  nokogiriSuccessfully  installed  nokogiri-­‐1.1.11  gem  installed

Page 102: Ruby

ruby-dbi

Page 103: Ruby

DBI.connect('DBI:SQLite3:test.db')  do  |dbh|    #  …end

Page 104: Ruby

dbh.prepare('INSERT  INTO  people  VALUES  (?)')  do  |sth|    sth.execute('Denis  Defreyne')    sth.execute('Wim  Vander  Schelden')    sth.execute('Sinterklaas')    sth.execute('Luke  Skywalker')end

Page 105: Ruby

activerecord

Page 106: Ruby

class  Person  <  ActiveRecord::Baseend

Page 107: Ruby

denis  =  Person.create(    :first_name  =>  'Denis',    :last_name  =>  'Defreyne')

wim  =  Person.create(    :first_name  =>  'Wim',    :last_name  =>  'Vander  Schelden')

Page 108: Ruby

p  =  Person.find_by_first_name('Denis')puts  "Last  name:  "  +  p.last_name

Page 109: Ruby

yaml

Page 110: Ruby

development:    driver:  sqlite3    dbfile:  myapp.db

production:    driver:  postgresql    dbname:  myapp    username:  bob    password:  4l1c3

Page 111: Ruby

config  =  YAML.load_file('config.yaml')

puts  config['production']['driver']#  postgresql

Page 112: Ruby

ramaze

Page 113: Ruby

class  MainController  <  Ramaze::Controller

   def  index        if  session[:ponies]            "OMG!!!  PONIES!!!"        else            "No  ponies  :("        end    end

   def  give_me_ponies        session[:ponies]  =  true        redirect  Rs(:index)    end

end

Page 114: Ruby

erb

Page 115: Ruby

Go  to  the  <%=  link_to  'Home  page',  :home  %>.

Page 116: Ruby

<ol  id="nav">    <li><%=  link_to  'home',              '/'                      %></li>    <li><%=  link_to  'journal',        '/journal/'      %></li>    <li><%=  link_to  'about',            '/about/'          %></li>    <li><%=  link_to  'software',      '/software/'    %></li>    <li><%=  link_to  'web  design',  '/webdesign/'  %></li>    <li><%=  link_to  'myst',              '/myst/'            %></li></ol>

Page 117: Ruby

rake

Page 118: Ruby

task  :foo  do    puts  "Doing  foo  stuff..."end

task  :default  =>  [  :foo  ]

Page 119: Ruby

▸  rake

Doing  foo  stuff...

Page 120: Ruby

you can hazquestions?