Ruby
-
Upload
denis-defreyne -
Category
Technology
-
view
1.425 -
download
2
description
Transcript of Ruby
Ruby
1. Taal
class Application{ public static void main(String[] args) { System.out.println("Hello World!"); }}
puts "Hello World!"
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 + '!'); }}
puts "What is your name?"name = gets.chompputs "Nice to meet you, #{name}!"
What is your name?DenisNice to meet you, Denis!
String name = new LibraryFactory(AbstractFactoryFactoryWeight().getFactoryAbstractFactory().getFactoryFactory().getFactory().getAbstractSystem().getConsoleFactory().getConsolable().injectDependency(ReadingFactory().getReader())).getLineFactory().getLine().read();
* * *
# dit is commentaar# dit is meer commentaarputs 'dit is geen commentaar'
a = 10
puts 'a is #{a}'puts "a is #{a}"
# output:# a is #{a}# a is 10
amount = 42
if amount == 42 puts "Perfect!"end
amount = 42
puts "Perfect!" if amount == 42
amount = 42
if amount < 10 puts "Not enough"elsif amount < 50 puts "Enough"else puts "Too much"end
names = [ 'Thomas', 'Dieter', 'Denis', 'Ruben', 'Hendrik', 'Niels', 'Wim', 'Wouter' ]
for name in names do puts "Hello #{name}"end
names = [ 'Thomas', 'Dieter', 'Denis', 'Ruben', 'Hendrik', 'Niels', 'Wim', 'Wouter' ]
names.each do |name| puts "Hello #{name}"end
names = [ 'Thomas', 'Dieter', 'Denis', 'Ruben', 'Hendrik', 'Niels', 'Wim', 'Wouter' ]
names.sort.each do |name| puts "Hello #{name}"end
(31..47).each do |i| puts iend
10.times do puts "Hello"end
count = 0while gets count += 1endputs "Number of lines: #{count}"
count = 0
count += 1 while gets
puts "Number of lines: #{count}"
def print_welcome_message puts "Hello!" puts "I am a function."end
print_welcome_message
def fact(n) if n == 0 return 1 else return n * fact(n-‐1) endend
puts fact(10)
def fact(n) if n == 0 1 else n * fact(n-‐1) endend
puts fact(10)
def fact(n) if n == 0 1 else n * fact(n-‐1) endend
puts fact(1000)
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
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
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
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
p = Person.new('Denis', 'Defreyne')puts "I am #{p.get_first_name}."
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
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end
end
p = Person.new('Denis', 'Defreyne')puts "I am #{p.first_name}."
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')]
people.each do |person| puts "-‐ #{person.first_name}"end
-‐ Denis-‐ Wim-‐ Dieter-‐ Ruben-‐ Niels-‐ Thomas-‐ Hendrik-‐ Wouter
some_people = people.select do |person| person.first_name =~ /^[A-‐M]/end
some_people.each do |person| puts "-‐ #{person.first_name}"end
-‐ Denis-‐ Dieter-‐ Hendrik
first_names = people.map do |person| person.first_nameend
first_names.each do |first_name| puts "-‐ #{first_name}"end
-‐ Denis-‐ Wim-‐ Dieter-‐ Ruben-‐ Niels-‐ Thomas-‐ Hendrik-‐ Wouter
first_names = people.map do |person| person.first_nameend
puts first_names.join(', ')
Denis, Wim, Dieter, Ruben, Niels, Thomas, Hendrik, Wouter
i = 0loop do puts "#{i}..." i += 1end
i = 0while i < 100 puts "#{i}..." i += 1end
:symbol
'string'
wim = { :first_name => 'Wim', :last_name => 'Verschelden'}
puts "Last name: #{wim[:last_name]}"
wim[:last_name] = 'Vander Schelden'puts "Last name: #{wim[:last_name]}"
if false puts "this message will not be printed"end
if nil puts "this message will not be printed"end
if 0 puts "this message will be printed"end
puts "Lorem ipsum dolor sit amet..."puts("Lorem ipsum dolor sit amet...")
my_list = []
if my_list.empty? puts "My list is empty :("end
my_list = [ 'foo', 'bar', 'baz' ]
if my_list.include?('foo') puts "My list includes 'foo'."end
class String def palindrome? self.reverse == self endend
if "straat".palindrome? puts "'straat' is een palindroom."else puts "'straat' is geen palindroom."end
words = [ 'racecar', 'daad', 'straat', 'koortsmeetsysteemstrook' ]
palindromes = words.select do |w| w.palindrome?end
palindromes.each { |p| puts p }
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 }
deedeeddeggedhallahkakkakmurdrumredderrepaperretterreviverrotatorsooloostebbetterret
email = '[email protected]'
puts email.sub('@', ' [AT] ')# denis.defreyne [AT] stoneship.org
puts email# [email protected]
email = '[email protected]'
email.sub!('@', ' [AT] ')puts email# denis.defreyne [AT] stoneship.org
module PalindromeChecking def palindrome? self.reverse == self endend
class String include PalindromeCheckingend
class Array include PalindromeCheckingend
puts 'racecar'.palindrome?# true
puts 'straat'.palindrome?# false
puts [ 1, 2, 4, 8, 4, 2, 1 ].palindrome?# true
puts [ 1, 2, 3, 4, 5, 6, 7 ].palindrome?# false
"asdf".blahblah
NoMethodError: undefined method `blahblah' for "asdf":String from (irb):1
nil.reverse
NoMethodError: undefined method `reverse' for nil:NilClass from (irb):2
nil.nil?# true
begin nil.reverserescue puts 'tis om zeep :('end
tis om zeep :(
def foobarize(s) raise ArgumentError.new('fail') unless s
'foobar'end
foobarize(nil)
ArgumentError: fail from (irb):8:in `foobarize' from (irb):12 from /usr/local/ruby/bin/irb:12:in `<main>'
begin foobarize(nil)rescue ArgumentError => e puts 'tis om zeep :(' puts e.inspectend
tis om zeep :(#<ArgumentError: fail>
def twice yield yieldend
twice do puts "Hello World"end
Hello WorldHello World
2. Testing
Unit Tests
class ExampleTest < Test::Unit::TestCase
def test_bob assert_equal('BOB', 'bob'.upcase) end
end
▸ testrb test.rb
Loaded suite test.rbStarted.Finished in 0.000341 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
class ExampleTest < Test::Unit::TestCase
def test_bob assert_equal('BOB', 'bob'.upcase) end
def test_mike assert_equal('BOB', 'mike'.upcase) end
end
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
▸ 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
Mocks + Stubs
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end
end
class PersonAnalyser
def initialize(person) @person = person end
def number_of_parts_in_last_name @person.last_name.split(/\s+/).size end
end
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
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
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
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
Loaded suite test.rbStarted....Finished in 0.000934 seconds.
4 tests, 4 assertions, 0 failures, 0 errors
Specs
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
it 'must be able to upcase strings' do 'bob'.upcase.must_equal 'BOB' 'mike'.upcase.must_equal 'MIKE'end
3. Tools
irb
▸ irb
irb(main):001:0> "Hello".reverse=> "olleH"irb(main):002:0> "Test".upcase=> "TEST"
nokogiri
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
rubygems
▸ ruby nokogiri-‐test.rbtest.rb:1:in `require': no such file to load -‐-‐ nokogiri (LoadError) from test.rb:1
▸ sudo gem install nokogiriSuccessfully installed nokogiri-‐1.1.11 gem installed
ruby-dbi
DBI.connect('DBI:SQLite3:test.db') do |dbh| # …end
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
activerecord
class Person < ActiveRecord::Baseend
denis = Person.create( :first_name => 'Denis', :last_name => 'Defreyne')
wim = Person.create( :first_name => 'Wim', :last_name => 'Vander Schelden')
p = Person.find_by_first_name('Denis')puts "Last name: " + p.last_name
yaml
development: driver: sqlite3 dbfile: myapp.db
production: driver: postgresql dbname: myapp username: bob password: 4l1c3
config = YAML.load_file('config.yaml')
puts config['production']['driver']# postgresql
ramaze
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
erb
Go to the <%= link_to 'Home page', :home %>.
<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>
rake
task :foo do puts "Doing foo stuff..."end
task :default => [ :foo ]
▸ rake
Doing foo stuff...
you can hazquestions?