ruby intro

43
Ruby

Upload: angelo-van-der-sijpt

Post on 16-May-2015

1.752 views

Category:

Technology


6 download

DESCRIPTION

For a company-meeting, I prepared an introduction to Ruby, showing the way I perceived it as a Java programmer. The original keynote file can be found at http://dl.dropbox.com/u/2438787/www/2009-11/Ruby%20intro%20-%20LSD%20meeting%2020091201.key The code examples in this presentation have been created using http://blog.pastie.org/2008/06/textmate-to-key.html .

TRANSCRIPT

Page 1: Ruby Intro

Ruby

Page 2: Ruby Intro

• Japan,  1993

• Perl,  Smalltalk,  Lisp

• Readability,  writability

Page 3: Ruby Intro

• English  language,  1999

• Windows,  Linux,  Mac  OS  X

• Included  with  Apple  developer  tools

Page 4: Ruby Intro

• “Everything  is  an  object.”• Except  for  primiNves.  But  you  can  box  those.

• Arrays  are  special.

• Classes  are  a  liQle  special,  too.

• “Everything  is  an  object.”• Period.

Page 5: Ruby Intro

1.class # => Fixnum'a'.class # => String:z.class # => Symbol

class Fooend

Foo.class # => ClassFoo.new.class # => Foo

Everything  is  an  object

Page 6: Ruby Intro

Dynamically  typeddef do_stuff(thing) thing.do_the_stuffend

class TheThing def do_the_stuff puts "Stuff was done!" endend

do_stuff(TheThing.new)

Page 7: Ruby Intro

Dynamically  typed

t = TheThing.newt.respond_to? :do_the_stuff # => true

def do_stuff(thing) if thing.respond_to? :do_the_stuff thing.do_the_stuff else raise "What on earth is this?" endend

Page 8: Ruby Intro

The  language

Page 9: Ruby Intro

Strings  &  variables

name = 'World' # => "World"

"Hello, #{name}" # => "Hello, World"

'Hello, #{name}' # => "Hello, \#{name}"

Page 10: Ruby Intro

Every  expression  has  a  value

def say_it_isnt_so(really = false) if really "All's fine!" else "All your base are belong to us." endend

say_it_isnt_so # => "All your base are belong to us."say_it_isnt_so true # => "All's fine!"

Page 11: Ruby Intro

Return

def do_complicated_stuff(take_shortcut) if take_shortcut return 42 end do_really_complicated_stuffend

Page 12: Ruby Intro

Numbers

1 + 1 # => 21 + 1.1 # => 2.16 * 7 # => 426 ** 7 # => 279936

Math.sqrt(65536) # => 256.0

1.class # => Fixnum(2 ** 42).class # => Fixnum(2 ** 64).class # => Bignum

1.1.class # => Float

Page 13: Ruby Intro

Arrays

Array.new # => []Array.new(3) # => [nil, nil, nil][] # => []

a = [1,2,3] # => [1, 2, 3]a[0] = 'one' # => "one"a # => ["one", 2, 3]a[-1] # => 3a[1..2] # => [2, 3]

Page 14: Ruby Intro

Arrays

a = [1,2,3] # => [1, 2, 3]

a.push 4 # => ["one", 2, 3, 4]a.pop # => 4a # => ["one", 2, 3]

[1,2,3] | [2, 4] # => [1, 2, 3, 4][1,2,3] & [2, 4] # => [2]

Page 15: Ruby Intro

Hashes

Hash.new # => {}{} # => {}

h = {1 => "one", 2 => "two"}h[1] # => "one"h["1"] # => nil

h[:one] = "einz" # => "einz"h[:one] # => "einz"

h.keys # => [1, 2, :one]h.values # => ["one", "two", "einz"]

Page 16: Ruby Intro

Fun  with  arrays  &  hashes

def do_stuff(options = {}) puts options[:hello] if options.include?(:hello)end

do_stuff# => nildo_stuff :hello => "hi"# hi# => nil

Page 17: Ruby Intro

Fun  with  arrays  &  hashes

[1,2,3,5,7].select {|x| x.even?}# => [2]

[1,2,3,5,7].inject(1) { |x, n| n * x}# => 210

[1,2,3,5,7].map { |n| n * n }# => [1, 4, 9, 25, 49]

{1 => "one", 2 => "two"}.map { |k,v| v }# => ["one", "two"]

Page 18: Ruby Intro

Control  structures

if condition # ...elsif other_condition # ...end

unless condition # ...end

while # ...end

Page 19: Ruby Intro

Control  structures

case (1024)when 42 then puts "my favorite number"when 2 then puts "my second favorite number"when 1024, 2048 then puts "fair enough"else "this number sucks"end

Page 20: Ruby Intro

Control  structures

puts "How are you gentlemen!!" if role.cats?

puts "mommy!" while reaction_from_mommy.nil?

Page 21: Ruby Intro

Classesclass Pet attr_accessor :name def initialize(name) @name = name end def sit! puts "Wuff" endend

fido = Pet.new("fido") # => #<Pet:0x10116e908 @name="fido">fido.name # => "fido"fido.sit! # => "Wuff"

Page 22: Ruby Intro

Classes

class Cat < Pet def sit! if rand(10) > 8 # decide our mood super else puts "No way!" end endend

mimi = Cat.new("mimi") # => #<Cat:0x101131d00 @name="mimi">mimi.sit! # => "No way!"

Page 23: Ruby Intro

Classes

class Cat def self.purr puts "Huh, what? I'm the class!" end def purr puts "prrrrrrr" endend

Cat.purr# "Huh, what? I'm the class!"Cat.new("mimi").purr# prrrrrrr

Page 24: Ruby Intro

Classes

class Fixnum def even? return false if eql? 2 super endend

2.even? # => false4.even? # => true

Page 25: Ruby Intro

Modules

module ThingsDoer def do_one_thing puts "doing one thing" endend

ThingsDoer::do_one_thing# "doing one thing"

# Modules can be used to group methods, classes or other modules

Page 26: Ruby Intro

Modules

class Pet include ThingsDoerend

# we had a Pet instance of fido

fido.do_one_thing# "doing one thing"

Page 27: Ruby Intro

Naming  convenDons

CamelCased # Classes, moduleswith_underscores # methods, local variables

@instance_variable@@class_variable$GLOBAL_VARIABLE

Page 28: Ruby Intro

Code  blocks[1,2,3,5,7].select {|x| x.even?}# => [2]

def do_random_nr_of_times &block nr = rand(10) for i in 1..nr yield endend

do_random_nr_of_times { puts "bla" }# bla# bla# bla# => 1..3

Page 29: Ruby Intro

Code  blocks

def run value = "bla" do_random_nr_of_times { puts value }endrun# bla# bla# => 1..2

Page 30: Ruby Intro

Code  blocks

the_time = Time.now # Sun Nov 29 20:15:47 0100 2009the_time# Sun Nov 29 20:15:47 0100 2009the_time# Sun Nov 29 20:15:47 0100 2009 >> the_time = lambda { Time.now }# => #<Proc:0x0000000100567178@(irb):463>the_time.call# Sun Nov 29 20:18:16 0100 2009the_time.call# Sun Nov 29 20:18:20 0100 2009

Page 31: Ruby Intro

OpDonal  language  elements

def my_method(data, options = {}) # ...end

# Full signaturemy_method("bla", {:option => 'value', :two => 2})# The last parameter a hash? implicit.my_method("bla", :option => 'value', :two => 2) # Parentheses are optionalmy_method "bla", :option => 'value', :two => 2

# As long as its unambiguous, it's OK

Page 32: Ruby Intro

Regular  expressions

s = "Ruby rules"# => "Ruby rules"s =~ /rules/# => 5s.gsub(/es/, "ez")# => "Ruby rulez"s.gsub(/[aeiou]/, "*")# => "R*by r*l*s"m = s.match(/([aeiou][^aeiou])/)# => #<MatchData "ub" 1:"ub">m[0]# => "ub"

Page 33: Ruby Intro

ExcepDonsbegin raise "Someone set us up the bomb."rescue => e puts e.inspectend# <RuntimeError: Someone set us up the bomb.>

begin raise StandardError.new("For great justice.")rescue StandardError puts "standard"rescue RuntimeError puts "runtime"end# standard

Page 34: Ruby Intro

• No  threading  (at  least,  by  default)

• Only  false  and  nil  are  not  true

What’s  more?

def my_method(my_object) puts my_object && my_object.to_sendmy_method(1) # => 1my_method(nil) # => nil

h[:bla] ||= "bla"

Page 35: Ruby Intro

Tools

Page 36: Ruby Intro

irb

Page 37: Ruby Intro

Textmate

Page 38: Ruby Intro

What  haven’t  I  talked  about?

• TesNng

• RSpec

• DocumentaNon

• RDoc

Page 39: Ruby Intro

What  haven’t  I  talked  about?

• Gems

• Like  ‘apt’  for  ruby

• Deployment

• SVN

• Capistrano

Page 40: Ruby Intro

What  haven’t  I  talked  about?

class BlogPost < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user_id validates_associated :user validates_length_of :title, :within => 10..100 validates_length_of :body, :within => 100..5000end

BlogPost.new(:title -> "My first blog", :body => "is way too short.")

Page 41: Ruby Intro

What  haven’t  I  talked  about?

• Ruby  on  Rails

• Web  framework

• Strict  MVC  separaNon

• Handles  persistence http://pragprog.com/titles/rails2

Page 42: Ruby Intro

module Ruby include(DynamicLanguage) include(ObjectOriented) include(DuckTyping)

def ruby @everything_is_an_object = true end def language {"hashes" => :awesome, "array" => :awesome} value = 'supported' "String variable substibution is #{value}" end

def tools {:editor => 'Textmate', :runtime => 'included in OS X'} endend

Page 43: Ruby Intro

thank_audience :speaker => 'Angelo vd Sijpt', :greeting => 'You were awesome!', :find_more_at ['ruby-lang.org', 'rubyists.eu']