SlideShare ist ein Scribd-Unternehmen logo
1 von 78
Intro to Ruby
Women Who Code Belfast

h.campbell@kainos.com : hcampbell07 : heatherjcampbell.com
Syntactic

Sugar

Productive
Developers
• Everything is an Expression

• Everything is an Object
• Supports Dynamic Reflection
GETTING STARTED
current_count = 5
final_salary = 30000.00

Snake Case
Readable
String.methods.sort
String.instance_methods.sort

Methods
my_array.empty?
person.retired?

True or False
str.upcase vs str.upcase!

Create New vs
Modify Existing
io.rb
print “Enter your name: ”
name = gets
puts name.strip + “ is learning Ruby”

Input / Output
[4,2,3,5].sort.map{ |e| e * e}.join(',')
# "4,9,16,25"

Method Chaining
• Write some code to ask a user to input a
number. Take the number multiply it by
10 and display it back to the user
• Find a method to capitalize a string
• Check the class of 1. (using the .class
method) then find a method to check if
the number is even

Exercises
TYPES
true.class
# TrueClass
false.class
# FalseClass
true.to_s
# "true"

Boolean
1.class
# Fixnum

1111111111.class
# Bignum

Fixnum.superclass
# Integer

Bignum.superclass
# Integer

111_000_000.class
# Fixnum

1.2345.class
# Float

Numbers
String.method.count
# Lots of helpful methods!
"Ruby" * 4
# "RubyRubyRubyRuby"
"Ruby" + " " + "Ruby"
# "Ruby Ruby"
a = "I don’t know Ruby"
a*"don’t"+ = "do"
# "I do know Ruby"

String
number_of_girls = 4
number_of_boys = 6
puts "number of girls #{number_of_girls}"
puts "number of boys #{number_of_boys}"
puts "number of people
#{number_of_boys + number_of_girls}"

Interpolation
phone = "(028 90)454 545"
phone.gsub!(/D/, "")
puts "Phone Number : #{phone}"
# "02890454545"

puts "Heather Campbell".gsub(/([a-zA-Z]+)
([a-zA-Z]+)/, "2, 1")
# "Campbell, Heather"

Regex
attr_accessor :driver
:small :medium :large
a = :small
b = :small
a.object_id == b.object_id
# true
:small.to_s
# "small "

"small".to_sym
# :small

Symbols
arr = [1,2,'three', :big]
arr.size # 4
arr.empty? # false
arr[1] # 2
arr[-1] # :big
arr[1..3] # [2,'three', :big]
arr[4..5] = [:east, :west]
# [1,2,'three', :big, :east, :west]
arr << 10
# [1,2,'three', :big, :east, :west,10]

Arrays
[1,2,3].map { |e| e * e}
# [1,4,9]
[2,2,3].reduce{|total,v| total * v}
# 12
['act', 'bat', 'them'] .all? { |w| w.length >= 3 }
# true

Enumerable
h = {'France' => 'Paris', 'Ireland' => 'Dublin' }
h = {France: 'Paris', Ireland: 'Dublin' }
h[:France]
# 'Paris‘
h[:Italy] = 'Rome'
# h = {France: 'Paris', Ireland: 'Dublin', Italy:
# 'Rome' }
h.each {|k,v| puts "key: #{k} t value: #{v}"}
h.any? { |k,v| v == 'Rome' }

Hashes
(1..5).each{|v| p v}
# 1,2,3,4,5
(1…5).each{|v| p v}
# 1,2,3,4
(10..20).include?(19) # true
(2..5).end # 5
("aa".."ae").each{|v| p v}
# "aa","ab","ac","ad","ae"

Ranges
def get_values; [1,2,3,4]; end;
first, _, _, last = get_values
# first = 1, last = 4
a, *b, c = get_values
# a = 1, b = [2,3],c = 4
r = (0..5)
a = [1,2,*r]
# a = [1,2,0,1,2,3,4,5]

Splat Operator
•
•

Separate an array [1,2,3,4] into 2 variables
one holding the head of the array (i.e 1) and
the other the rest of the array [2,3,4]
Create a hash of months and days in a month
e.g. {January: 31, ..}. For each month print out
the month name and number of days. Then
print out totals days in year by summing the
hashes values

Exercises
FLOW CONTROL
if mark > 75
report = "great"
elsif mark > 50
report = "good"
else
report = "needs work"
end

report =
if mark > 75 then
"great"
elsif mark > 50 then
"good"
else
"needs work"
end

if else
if !order.nil?
order.calculate_tax
end
order.calculate_tax unless order.nil?

unless
speed = 60
limit = 40
speed > limit ? puts("Speeding!") : puts("Within
Limit")

ternary operator
mark = 42 && mark * 2
# translates to mark = (42 && mark) * 2
mark = 42 and mark * 2
# returns 84
post = Posts.locate(post_id) and post.publish
# publishes post if it is located
if engine.cut_out?
engine.restart or enable_emergency_power
end

and / or
grade = case mark
when 90..100
"A"
when 70..89
"B"
when 60..69
"C"
when 50..59
"D"
when 40..49
"E"
else
"F"
end

case unit
when String
puts "A String!"
when TrueClass
puts "So True!"
when FalseClass
puts "So False!"
end

case
while count < max
puts "Inside the loop. count = #{count}"
count +=1
end
puts "count = #{count += 1}" while count < max

while
until count > max
puts "Inside the loop. count = #{count}"
count +=1
end
array = [1,2,3,4,5,6,7]
array.pop until array.length < 3

until
begin
puts "Inside the loop. count = #{count}"
count +=1
end while count < max

looping block
for count in (1..10)
puts "Inside the loop: count = #{count}"
end

for
animals = {cat: "meow ", cow: "moo "}

animals.each do |k,v|
puts "The #{k} goes #{v}"
end
animals = {cat: "meow ", cow: "moo "}

animals.each {|k,v| puts "The #{k} goes #{v} "}

iterators
magic_number = 5; found = false; i = 0; input = 0;
while i < 3
print "Please enter a number between 1 and 10: "
input = gets.to_i
unless input.between?(1,10)
print "invalid number"; redo
end
if input == magic_number
found = true; break
end
i += 1
end
found ? put "found! " : put " bad luck "

flow control
def display_content(name)
f = File.open(name, 'r')
line_num=0
# raise 'A test exception.'
f.each {|line| print "#{line_num += 1} #{line}"}
rescue Exception => e
puts "ooops"; puts e.message; puts e.backtrace
else
puts "nSuccessfully displayed!"
ensure
if f then f.close; puts "file safely closed"; end
end

exception handling
def get_patients()
patients = API.request("/patients")
rescue RuntimeError => e
attempts ||= 0
attempts += 1
if attempts < 3
puts e.message + ". Retrying request. “
retry
else
puts "Failed to retrieve patients"
raise
end
end

exception handling
•
•
•
•

Write some conditional logic to capitalize a
string if it is not in uppercase
Print out your name 10 times
Print the string “This is sentence number 1”
where the number 1 changes from 1 to 10
Write a case statements which outputs
“Integer” if the variable is an integer, “Float” if
it is a floating point number or else “don’t
know!”

Exercises
CLASSES
class Vehicle
def drive(destination)
@destination = destination
end

end

Classes
class Vehicle
attr_accessor :destination

def drive(destination)
self.destination = destination
# do more drive stuff
end
end

Accessors
attr_accessor
attr_reader
attr_writer

Accessors
class Vehicle
attr_accessor :colour, :make
def initialize(colour, make)
@make = make
@colour = colour
end
end

Constructor
class SuperCar < Vehicle
def drive(destination)
self.destination = destination
puts 'driving super fast'
end
end

Inheritance
class SuperCar < Vehicle
attr_accessor :driver

def drive(circuit, driver)
self.destination = destination
self.driver = driver
puts 'driving super fast'
end
end

Inheritance
“If it walks like a duck and talks
like a duck, it must be a duck”

Duck Typing
class Person
def quack()
puts 'pretends to quack'
end
end
class Duck
def quack()
puts 'quack quack'
end
end

Duck Typing
def call_quack(duck)
duck.quack
end
call_quack(Duck.new)
# quack quack

call_quack(Person.new)
# pretends to quack

Duck Typing
class Vehicle

class Vehicle

def crash()
explode
end

def crash()
explode
end

private
def explode()
puts "Boom!"
end
end

def explode()
puts "Boom!"
end
private :explode
end

Method Visibility
class SuperCar < Vehicle
def explode()
puts "Massive Boom!"
end
end

Method Visibility
result = class Test
answer = 7+5
puts " Calculating in class: " + answer.to_s
answer
end
puts "Output of the class: " + result.to_s

Executable
class Rocket
….

end

r = Rocket.new
class Rocket
def land()
puts "Back on Earth"
end
end

r.land

Open Classes
class String
def shout
self.upcase!
self + "!!!"
end
def empty?
true
end
end

Monkey Patching
a = "abc"
b=a
c = "abc"
a.equal?(b)
# true
a.equal?(c)
# false
a == b
# true
a == c
# true

Equality
•
•
•
•
•
•

Create a class to represent a Computer
Create an instance of the Computer called
computer
Add a starting_up method
Create a class WindowsComputer which
inherits from Computer
Create an instance of the WindowsComputer
called wcomputer and call starting_up on it
Alter WindowsComputer to allow the user to
set a name value when they create an
instance. Allow the user to set and get the
name attribute

Exercises
METHODS
# Java
public Car() , …public Car(String make) { }
public Car(String make, String model) { }
public Car(String make, String model, String colour) { }
# Ruby
def initialize (make = :Ford,
model = Car.get_default_model(make),
colour = (make == :Ferrari ? 'red' : 'silver') )
…
end

Overloading Methods
def create_car (make = :Ford,
model = get_default_model(make),
colour)
…
end
create_car('red' )

Method Parameters
def produce_student(name, *subjects)
…
end
produce_student('June Black', 'Chemistry',
'Maths', 'Computing' )
subject_list = ['Chemistry', 'Maths', 'Computing']
produce_student('June Black', *subject_list)

Variable Length Param List
class Meteor
attr_accessor :speed
def initialize()
@speed = 0
end
def +(amt)
@speed += amt
end
def -(amt)
@speed > amt ? (@speed -= amt) : (@speed = 0)
end
end

Operators
class Roman
def self.method_missing name, *args
roman = name.to_s
roman.gsub!("IV", "IIII")
roman.gsub!("IX", "VIIII")
roman.gsub!("XL", "XXXX")
roman.gsub!("XC", "LXXXX")
(roman.count("I") +
roman.count("V") * 5 +
roman.count("X") * 10 +
roman.count("L") * 50 +
roman.count("C") * 100)
end
end

Method
Missing
handlers = { up_arrow: :tilt_up,
down_arrow: :tilt_down,
left_arrow: :turn_left,
right_arrow: :turn_right}
ship.__send__(handlers[input])

Send
•
•
•
•
•
•

Alter the WindowsComputer class you created in the
last exercise to make the name parameter optional
Try creating an instance with and without a name
value
Add a mandatory attribute called owner to the class
and alter initialize to set it.
Try creating a new instance with no, 1 and 2
parameter values. What happens?
add a method display_details to output the name
and owner of the machine and try calling it using
__send__
now make display_details private and try calling it
directly and using __send__. Notice anything odd?

Exercises
OTHER FEATURES
def block_example
puts 'Optional block example.'
if block_given?
yield "Heather"
else
puts 'No block. Very Empty'
end
puts 'End of example'
end

Blocks
def with_timing
start = Time.now
if block_given?
yield
puts 'Time taken:
#{Time.now - start}'
end
end

Blocks
def add_numbers(x, y)
x+y
end
alter the above method to accept a block and
execute it if one is supplied. Call it with a block to
provide debug i.e. displaying the method name
and values passed

Exercises
TESTING
Test
Driven
Development
Behaviour
Driven
Development
require 'minitest/autorun'
require '../lib/People'
class TestEmployee < MiniTest::Unit::TestCase
def setup
@employee = Employee.new
end
def test_employer
assert_equal "Kainos", @employee.employer
end

end

MiniTest
require "minitest/autorun"
describe Employee do
before do
@employee = Employee.new
end
describe "when asked for an employer" do
it "must provide one" do
@employee.employer.must_equal "Kainos"
end
end
end

MiniTest
# bowling_spec.rb
require 'bowling'
describe Bowling, "#score" do
it "returns 0 for all gutter game" do
bowling = Bowling.new
20.times { bowling.hit(0) }
bowling.score.should eq(0)
end
end

RSpec
# division.feature
Feature: Division
In order to avoid silly mistakes
Cashiers must be able to calculate a fraction
Scenario: Regular numbers
* I have entered 3 into the calculator
* I have entered 2 into the calculator
* I press divide
* the result should be 1.5 on the screen

Cucumber
#calculator_steps.rb

Before do
@calc = Calculator.new
end
Given /I have entered (d+) into the calculator/ do
|n|
@calc.push n.to_i
end
When /I press (w+)/ do |op|
@result = @calc.send op
end

Cucumber
Want to Learn More?
Codecademy
http://www.codecademy.com/tracks/ruby

CodeSchool
https://www.codeschool.com/paths/ruby

Seven Languages in Seven Weeks
pragprog.com/book/btlang/seven-languages-in-seven-weeks
Want to Learn More?
Programming Ruby

pragprog.com/book/ruby/programming-ruby
First edition available for free online at
http://ruby-doc.com/docs/ProgrammingRuby/

Ruby Koans
http://rubykoans.com

Pluralsight
Any Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into SwiftSarath C
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent typesbmlever
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)Scott Wlaschin
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6Abdul Haseeb
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kianphelios
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
Python programming workshop session 4
Python programming workshop session 4Python programming workshop session 4
Python programming workshop session 4Abdul Haseeb
 
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
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 

Was ist angesagt? (20)

Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent types
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
What are monads?
What are monads?What are monads?
What are monads?
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Python programming workshop session 4
Python programming workshop session 4Python programming workshop session 4
Python programming workshop session 4
 
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
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 

Andere mochten auch

Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...
Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...
Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...TALiNT Partners
 
Heather Campbell Resume with skills
Heather Campbell Resume with skillsHeather Campbell Resume with skills
Heather Campbell Resume with skillsHeather Campbell
 
SCampbell Unofficial Transcript.PDF
SCampbell Unofficial Transcript.PDFSCampbell Unofficial Transcript.PDF
SCampbell Unofficial Transcript.PDFStephen Campbell
 
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...CCT International
 

Andere mochten auch (7)

Campbell Resume
Campbell ResumeCampbell Resume
Campbell Resume
 
The Importance of Devops
The Importance of DevopsThe Importance of Devops
The Importance of Devops
 
Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...
Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...
Feel the Fear… And Don’t Do It Anyway Heather Campbell, Managing Director, Co...
 
Heather Campbell Resume with skills
Heather Campbell Resume with skillsHeather Campbell Resume with skills
Heather Campbell Resume with skills
 
Stephen Campbell Resume
Stephen Campbell ResumeStephen Campbell Resume
Stephen Campbell Resume
 
SCampbell Unofficial Transcript.PDF
SCampbell Unofficial Transcript.PDFSCampbell Unofficial Transcript.PDF
SCampbell Unofficial Transcript.PDF
 
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...
Integrating BIM and LEAN for Project Delivery - Construction of a Major Hospi...
 

Ähnlich wie Intro to ruby

Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Benjamin Bock
 
Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Fred Heath
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
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
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 

Ähnlich wie Intro to ruby (20)

Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015Design Patterns the Ruby way - ConFoo 2015
Design Patterns the Ruby way - ConFoo 2015
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Ruby
RubyRuby
Ruby
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
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
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 

Kürzlich hochgeladen

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Kürzlich hochgeladen (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Intro to ruby

  • 1. Intro to Ruby Women Who Code Belfast h.campbell@kainos.com : hcampbell07 : heatherjcampbell.com
  • 3. • Everything is an Expression • Everything is an Object • Supports Dynamic Reflection
  • 5. current_count = 5 final_salary = 30000.00 Snake Case Readable
  • 8. str.upcase vs str.upcase! Create New vs Modify Existing
  • 9. io.rb print “Enter your name: ” name = gets puts name.strip + “ is learning Ruby” Input / Output
  • 10. [4,2,3,5].sort.map{ |e| e * e}.join(',') # "4,9,16,25" Method Chaining
  • 11. • Write some code to ask a user to input a number. Take the number multiply it by 10 and display it back to the user • Find a method to capitalize a string • Check the class of 1. (using the .class method) then find a method to check if the number is even Exercises
  • 12. TYPES
  • 14. 1.class # Fixnum 1111111111.class # Bignum Fixnum.superclass # Integer Bignum.superclass # Integer 111_000_000.class # Fixnum 1.2345.class # Float Numbers
  • 15. String.method.count # Lots of helpful methods! "Ruby" * 4 # "RubyRubyRubyRuby" "Ruby" + " " + "Ruby" # "Ruby Ruby" a = "I don’t know Ruby" a*"don’t"+ = "do" # "I do know Ruby" String
  • 16. number_of_girls = 4 number_of_boys = 6 puts "number of girls #{number_of_girls}" puts "number of boys #{number_of_boys}" puts "number of people #{number_of_boys + number_of_girls}" Interpolation
  • 17. phone = "(028 90)454 545" phone.gsub!(/D/, "") puts "Phone Number : #{phone}" # "02890454545" puts "Heather Campbell".gsub(/([a-zA-Z]+) ([a-zA-Z]+)/, "2, 1") # "Campbell, Heather" Regex
  • 18. attr_accessor :driver :small :medium :large a = :small b = :small a.object_id == b.object_id # true :small.to_s # "small " "small".to_sym # :small Symbols
  • 19. arr = [1,2,'three', :big] arr.size # 4 arr.empty? # false arr[1] # 2 arr[-1] # :big arr[1..3] # [2,'three', :big] arr[4..5] = [:east, :west] # [1,2,'three', :big, :east, :west] arr << 10 # [1,2,'three', :big, :east, :west,10] Arrays
  • 20. [1,2,3].map { |e| e * e} # [1,4,9] [2,2,3].reduce{|total,v| total * v} # 12 ['act', 'bat', 'them'] .all? { |w| w.length >= 3 } # true Enumerable
  • 21. h = {'France' => 'Paris', 'Ireland' => 'Dublin' } h = {France: 'Paris', Ireland: 'Dublin' } h[:France] # 'Paris‘ h[:Italy] = 'Rome' # h = {France: 'Paris', Ireland: 'Dublin', Italy: # 'Rome' } h.each {|k,v| puts "key: #{k} t value: #{v}"} h.any? { |k,v| v == 'Rome' } Hashes
  • 22. (1..5).each{|v| p v} # 1,2,3,4,5 (1…5).each{|v| p v} # 1,2,3,4 (10..20).include?(19) # true (2..5).end # 5 ("aa".."ae").each{|v| p v} # "aa","ab","ac","ad","ae" Ranges
  • 23. def get_values; [1,2,3,4]; end; first, _, _, last = get_values # first = 1, last = 4 a, *b, c = get_values # a = 1, b = [2,3],c = 4 r = (0..5) a = [1,2,*r] # a = [1,2,0,1,2,3,4,5] Splat Operator
  • 24. • • Separate an array [1,2,3,4] into 2 variables one holding the head of the array (i.e 1) and the other the rest of the array [2,3,4] Create a hash of months and days in a month e.g. {January: 31, ..}. For each month print out the month name and number of days. Then print out totals days in year by summing the hashes values Exercises
  • 26. if mark > 75 report = "great" elsif mark > 50 report = "good" else report = "needs work" end report = if mark > 75 then "great" elsif mark > 50 then "good" else "needs work" end if else
  • 28. speed = 60 limit = 40 speed > limit ? puts("Speeding!") : puts("Within Limit") ternary operator
  • 29. mark = 42 && mark * 2 # translates to mark = (42 && mark) * 2 mark = 42 and mark * 2 # returns 84 post = Posts.locate(post_id) and post.publish # publishes post if it is located if engine.cut_out? engine.restart or enable_emergency_power end and / or
  • 30. grade = case mark when 90..100 "A" when 70..89 "B" when 60..69 "C" when 50..59 "D" when 40..49 "E" else "F" end case unit when String puts "A String!" when TrueClass puts "So True!" when FalseClass puts "So False!" end case
  • 31. while count < max puts "Inside the loop. count = #{count}" count +=1 end puts "count = #{count += 1}" while count < max while
  • 32. until count > max puts "Inside the loop. count = #{count}" count +=1 end array = [1,2,3,4,5,6,7] array.pop until array.length < 3 until
  • 33. begin puts "Inside the loop. count = #{count}" count +=1 end while count < max looping block
  • 34. for count in (1..10) puts "Inside the loop: count = #{count}" end for
  • 35. animals = {cat: "meow ", cow: "moo "} animals.each do |k,v| puts "The #{k} goes #{v}" end animals = {cat: "meow ", cow: "moo "} animals.each {|k,v| puts "The #{k} goes #{v} "} iterators
  • 36. magic_number = 5; found = false; i = 0; input = 0; while i < 3 print "Please enter a number between 1 and 10: " input = gets.to_i unless input.between?(1,10) print "invalid number"; redo end if input == magic_number found = true; break end i += 1 end found ? put "found! " : put " bad luck " flow control
  • 37. def display_content(name) f = File.open(name, 'r') line_num=0 # raise 'A test exception.' f.each {|line| print "#{line_num += 1} #{line}"} rescue Exception => e puts "ooops"; puts e.message; puts e.backtrace else puts "nSuccessfully displayed!" ensure if f then f.close; puts "file safely closed"; end end exception handling
  • 38. def get_patients() patients = API.request("/patients") rescue RuntimeError => e attempts ||= 0 attempts += 1 if attempts < 3 puts e.message + ". Retrying request. “ retry else puts "Failed to retrieve patients" raise end end exception handling
  • 39. • • • • Write some conditional logic to capitalize a string if it is not in uppercase Print out your name 10 times Print the string “This is sentence number 1” where the number 1 changes from 1 to 10 Write a case statements which outputs “Integer” if the variable is an integer, “Float” if it is a floating point number or else “don’t know!” Exercises
  • 41. class Vehicle def drive(destination) @destination = destination end end Classes
  • 42. class Vehicle attr_accessor :destination def drive(destination) self.destination = destination # do more drive stuff end end Accessors
  • 44. class Vehicle attr_accessor :colour, :make def initialize(colour, make) @make = make @colour = colour end end Constructor
  • 45. class SuperCar < Vehicle def drive(destination) self.destination = destination puts 'driving super fast' end end Inheritance
  • 46. class SuperCar < Vehicle attr_accessor :driver def drive(circuit, driver) self.destination = destination self.driver = driver puts 'driving super fast' end end Inheritance
  • 47. “If it walks like a duck and talks like a duck, it must be a duck” Duck Typing
  • 48. class Person def quack() puts 'pretends to quack' end end class Duck def quack() puts 'quack quack' end end Duck Typing
  • 49. def call_quack(duck) duck.quack end call_quack(Duck.new) # quack quack call_quack(Person.new) # pretends to quack Duck Typing
  • 50. class Vehicle class Vehicle def crash() explode end def crash() explode end private def explode() puts "Boom!" end end def explode() puts "Boom!" end private :explode end Method Visibility
  • 51. class SuperCar < Vehicle def explode() puts "Massive Boom!" end end Method Visibility
  • 52. result = class Test answer = 7+5 puts " Calculating in class: " + answer.to_s answer end puts "Output of the class: " + result.to_s Executable
  • 53. class Rocket …. end r = Rocket.new class Rocket def land() puts "Back on Earth" end end r.land Open Classes
  • 54. class String def shout self.upcase! self + "!!!" end def empty? true end end Monkey Patching
  • 55. a = "abc" b=a c = "abc" a.equal?(b) # true a.equal?(c) # false a == b # true a == c # true Equality
  • 56. • • • • • • Create a class to represent a Computer Create an instance of the Computer called computer Add a starting_up method Create a class WindowsComputer which inherits from Computer Create an instance of the WindowsComputer called wcomputer and call starting_up on it Alter WindowsComputer to allow the user to set a name value when they create an instance. Allow the user to set and get the name attribute Exercises
  • 58. # Java public Car() , …public Car(String make) { } public Car(String make, String model) { } public Car(String make, String model, String colour) { } # Ruby def initialize (make = :Ford, model = Car.get_default_model(make), colour = (make == :Ferrari ? 'red' : 'silver') ) … end Overloading Methods
  • 59. def create_car (make = :Ford, model = get_default_model(make), colour) … end create_car('red' ) Method Parameters
  • 60. def produce_student(name, *subjects) … end produce_student('June Black', 'Chemistry', 'Maths', 'Computing' ) subject_list = ['Chemistry', 'Maths', 'Computing'] produce_student('June Black', *subject_list) Variable Length Param List
  • 61. class Meteor attr_accessor :speed def initialize() @speed = 0 end def +(amt) @speed += amt end def -(amt) @speed > amt ? (@speed -= amt) : (@speed = 0) end end Operators
  • 62. class Roman def self.method_missing name, *args roman = name.to_s roman.gsub!("IV", "IIII") roman.gsub!("IX", "VIIII") roman.gsub!("XL", "XXXX") roman.gsub!("XC", "LXXXX") (roman.count("I") + roman.count("V") * 5 + roman.count("X") * 10 + roman.count("L") * 50 + roman.count("C") * 100) end end Method Missing
  • 63. handlers = { up_arrow: :tilt_up, down_arrow: :tilt_down, left_arrow: :turn_left, right_arrow: :turn_right} ship.__send__(handlers[input]) Send
  • 64. • • • • • • Alter the WindowsComputer class you created in the last exercise to make the name parameter optional Try creating an instance with and without a name value Add a mandatory attribute called owner to the class and alter initialize to set it. Try creating a new instance with no, 1 and 2 parameter values. What happens? add a method display_details to output the name and owner of the machine and try calling it using __send__ now make display_details private and try calling it directly and using __send__. Notice anything odd? Exercises
  • 66. def block_example puts 'Optional block example.' if block_given? yield "Heather" else puts 'No block. Very Empty' end puts 'End of example' end Blocks
  • 67. def with_timing start = Time.now if block_given? yield puts 'Time taken: #{Time.now - start}' end end Blocks
  • 68. def add_numbers(x, y) x+y end alter the above method to accept a block and execute it if one is supplied. Call it with a block to provide debug i.e. displaying the method name and values passed Exercises
  • 71. require 'minitest/autorun' require '../lib/People' class TestEmployee < MiniTest::Unit::TestCase def setup @employee = Employee.new end def test_employer assert_equal "Kainos", @employee.employer end end MiniTest
  • 72. require "minitest/autorun" describe Employee do before do @employee = Employee.new end describe "when asked for an employer" do it "must provide one" do @employee.employer.must_equal "Kainos" end end end MiniTest
  • 73. # bowling_spec.rb require 'bowling' describe Bowling, "#score" do it "returns 0 for all gutter game" do bowling = Bowling.new 20.times { bowling.hit(0) } bowling.score.should eq(0) end end RSpec
  • 74. # division.feature Feature: Division In order to avoid silly mistakes Cashiers must be able to calculate a fraction Scenario: Regular numbers * I have entered 3 into the calculator * I have entered 2 into the calculator * I press divide * the result should be 1.5 on the screen Cucumber
  • 75. #calculator_steps.rb Before do @calc = Calculator.new end Given /I have entered (d+) into the calculator/ do |n| @calc.push n.to_i end When /I press (w+)/ do |op| @result = @calc.send op end Cucumber
  • 76. Want to Learn More? Codecademy http://www.codecademy.com/tracks/ruby CodeSchool https://www.codeschool.com/paths/ruby Seven Languages in Seven Weeks pragprog.com/book/btlang/seven-languages-in-seven-weeks
  • 77. Want to Learn More? Programming Ruby pragprog.com/book/ruby/programming-ruby First edition available for free online at http://ruby-doc.com/docs/ProgrammingRuby/ Ruby Koans http://rubykoans.com Pluralsight

Hinweis der Redaktion

  1. sees everything as an object even things other languages represent as primitivesa = 4.5a.classString.public_methods.sortString.superclass
  2. b = [] b.empty? c = “” c.empty? c.nil?
  3. Dangerous a = “abcde” a.upcase a a.upcase! a
  4. readonly
  5. used a lot in Ruby. Cleaner and more performant than concatenation. Doesn’t require creation of multiple strings
  6. Global unique and immutable, good substitute for string where like label e.g. hash keys,
  7. can also + to join and *
  8. Close to 50 methods v powerful
  9. also includes enumerable module
  10. can also + to join and *
  11. works with any class with implements to_a method
  12. operators to control flow. Chaining events. and if this is true then do this. or like a fallback try this or try this
  13. tend to use each construct instead. Use with ranges
  14. tend to use each construct instead. Use with ranges
  15. break: exits out of loop. In this case because we’ve found number, redo repeats iteration without re-evaluating the loop conditionnext: starts next iteration of loop without completing the current loop
  16. rescue: handling if an exception occures, else: only executed if no error occurred, ensure: always executed…tidying up!
  17. making a call to web service to retrieve list of patients. Sometimes it temp is unavailable, allowed 3 attempts before failingnote conditional initialization of attempts
  18. vehicle = vehicle.newvehicle.drive(“Bangor”)puts vehicle.inspectp vehicleVehicle.methodsVehicle.instance_methodsVehicle.instance_methods(false)
  19. vehicle = vehicle.newvehicle.drive(“Bangor”)puts vehicle.inspectp vehicleVehicle.methodsVehicle.instance_methodsVehicle.instance_methods(false)
  20. read/write, read only, write only
  21. called on new
  22. Overridden method, same initialize method, same attributes
  23. Overridden method, same initialize method, same attributes
  24. What method it understands is key not it’s type or parents
  25. 2 v different classes both with a quack method
  26. Overridden method, same initialize method, same attributes
  27. instance variables/attributes private by defaultinstance methods public by defaultprivate / protectedprivate can be called by subclasses. can’t be called with explicit object receiverprotected objs of sames class, obj with same ancestor if defined in the ancestor
  28. If you override method you need to explicitly set visibiliy again e.g. overridden explode method is public
  29. real uses are attr_accessor, private etc.http://ruby-doc.org/core-1.9.3/Module.html
  30. In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever&apos;s there.
  31.  extend or modify the run-time code of dynamic languages without altering the original source code. (third party libs)Power use wisely. Just becase you can do something doesn’t mean you should do it. Unexpected behaviour, assumptions made in how you change it may not be valid as versions of class change
  32. Can’t do it! Same method name but different param lists. instead can have optional paramsdefault values, method calls, conditional logic. calculated at the point of method call
  33. Can override operators. use sparingly where it makes code more readable. can cause unexpected behaviour for user and be cryptic to read
  34. Methods sent as messages to object instance. Receives it and looks to see if method exists anywhere in hierarchy if it does calls method with provided parameters
  35. Piece of code between do and end (multiline) or { single line} which can be passed as an arg to certain methods
  36. Avoid boiler plate code like timing, transactions
  37. TDD write test first and then just enough code to make it pass then repeatBDD specialised version of TDD where tests are defined in a format that is meaningful to the business, in terms of domain