Ruby
• Japan,	
  1993

• Perl,	
  Smalltalk,	
  Lisp

• Readability,	
  writability
• English	
  language,	
  1999

• Windows,	
  Linux,	
  Mac	
  OS	
  X

  • Included	
  with	
  Apple	
  developer	
  tools
• “Everything	
  is	
  an	
  object.”
                      •   Except	
  for	
  primiNves.	
  But	
  you	
  can	
  box	
 ...
Everything	
  is	
  an	
  object

1.class           # => Fixnum
'a'.class         # => String
:z.class          # => Symbo...
Dynamically	
  typed
def do_stuff(thing)
  thing.do_the_stuff
end

class TheThing
  def do_the_stuff
    puts "Stuff was d...
Dynamically	
  typed
t = TheThing.new
t.respond_to? :do_the_stuff   # => true

def do_stuff(thing)
  if thing.respond_to? ...
The	
  language
Strings	
  &	
  variables



name = 'World'   # => "World"

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

'Hello, #{name}' # => "H...
Every	
  expression	
  has	
  a	
  value


def say_it_isnt_so(really = false)
  if really
    "All's fine!"
  else
    "Al...
Return



def do_complicated_stuff(take_shortcut)
  if take_shortcut
    return 42
  end
  do_really_complicated_stuff
end
Numbers

1   + 1           #   =>   2
1   + 1.1         #   =>   2.1
6   * 7           #   =>   42
6   ** 7          #   =...
Arrays


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

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




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

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

h = {1 => "one", 2 => "two"}
h[1]                 # =...
Fun	
  with	
  arrays	
  &	
  hashes


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

...
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}
# =...
Control	
  structures

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

unless condition
  # ...
end

while
  # ......
Control	
  structures



case   (1024)
when   42 then puts "my favorite number"
when   2 then puts "my second favorite num...
Control	
  structures


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




puts "mommy!" while reaction_from_mommy.nil?
class Pet                      Classes
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def sit!
  ...
Classes

class Cat < Pet
  def sit!
    if rand(10) > 8 # decide our mood
      super
    else
      puts "No way!"
    en...
Classes
class Cat
  def self.purr
    puts "Huh, what? I'm the class!"
  end

  def purr
    puts "prrrrrrr"
  end
end

Ca...
Classes


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

2.even? # => false
4.even? # => true
Modules
       module ThingsDoer
         def do_one_thing
           puts "doing one thing"
         end
       end

    ...
Modules


class Pet
  include ThingsDoer
end

# we had a Pet instance of fido

fido.do_one_thing
# "doing one thing"
Naming	
  convenDons



CamelCased       # Classes, modules
with_underscores # methods, local variables

@instance_variabl...
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..n...
Code	
  blocks


def run
  value = "bla"
  do_random_nr_of_times { puts value }
end
run
# bla
# bla
# => 1..2
Code	
  blocks
the_time = Time.now
# Sun Nov 29 20:15:47 0100 2009
the_time
# Sun Nov 29 20:15:47 0100 2009
the_time
# Sun...
OpDonal	
  language	
  elements

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

# Full signature
my_method("bla", {:option...
Regular	
  expressions

s = "Ruby rules"
# => "Ruby rules"
s =~ /rules/
# => 5
s.gsub(/es/, "ez")
# => "Ruby rulez"
s.gsub...
ExcepDons
begin
  raise "Someone set us up the bomb."
rescue => e
  puts e.inspect
end
# <RuntimeError: Someone set us up ...
What’s	
  more?


• No	
  threading	
  (at	
  least,	
  by	
  default)
• Only	
  false	
  and	
  nil	
  are	
  not	
  true...
Tools
irb
Textmate
What	
  haven’t	
  I	
  talked	
  about?



• TesNng
 • RSpec
• DocumentaNon
 • RDoc
What	
  haven’t	
  I	
  talked	
  about?


• Gems
 • Like	
  ‘apt’	
  for	
  ruby
• Deployment
 • SVN
 • Capistrano
What	
  haven’t	
  I	
  talked	
  about?
class BlogPost < ActiveRecord::Base
  belongs_to :user
  has_many :comments

  va...
What	
  haven’t	
  I	
  talked	
  about?



• Ruby	
  on	
  Rails
  • Web	
  framework
  • Strict	
  MVC	
  separaNon
  • ...
module Ruby
  include(DynamicLanguage)
  include(ObjectOriented)
  include(DuckTyping)

  def ruby
    @everything_is_an_o...
thank_audience
  :speaker => 'Angelo vd Sijpt',
  :greeting => 'You were awesome!',
  :find_more_at ['ruby-lang.org',
    ...
Upcoming SlideShare
Loading in …5
×

Ruby Intro

2,348 views

Published on

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 .

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,348
On SlideShare
0
From Embeds
0
Number of Embeds
59
Actions
Shares
0
Downloads
54
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • I have been doing Ruby on Rails for about six weeks now; time for a quick introduction!
    This is not intended as a be-all-and-end-all presentation; I point out the things I find interesting or surprising.

    Image: http://shakti.trincoll.edu/~dmerrick/images/ruby.png
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Image: http://ifup.org/images/duke.gif
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Symbol can be seen as a constant without any overhead. Used for indexing, as key, etc.
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • Ruby uses the message metaphor for methods &amp; message; you send a symbol, and the object responds

    Duck typing &amp; inspection
  • the lambda method turns a codeblock into a &amp;#x2018;real&amp;#x2019; object
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Greatly increases readability!
  • Image: http://blogs.nitobi.com/alexei/wp-content/uploads/2008/04/ruby_on_rails_logo.jpg
  • Image: http://blogs.nitobi.com/alexei/wp-content/uploads/2008/04/ruby_on_rails_logo.jpg
  • Ruby Intro

    1. 1. Ruby
    2. 2. • Japan,  1993 • Perl,  Smalltalk,  Lisp • Readability,  writability
    3. 3. • English  language,  1999 • Windows,  Linux,  Mac  OS  X • Included  with  Apple  developer  tools
    4. 4. • “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.
    5. 5. Everything  is  an  object 1.class # => Fixnum 'a'.class # => String :z.class # => Symbol class Foo end Foo.class # => Class Foo.new.class # => Foo
    6. 6. Dynamically  typed def do_stuff(thing) thing.do_the_stuff end class TheThing def do_the_stuff puts "Stuff was done!" end end do_stuff(TheThing.new)
    7. 7. Dynamically  typed t = TheThing.new t.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?" end end
    8. 8. The  language
    9. 9. Strings  &  variables name = 'World' # => "World" "Hello, #{name}" # => "Hello, World" 'Hello, #{name}' # => "Hello, #{name}"
    10. 10. 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." end end say_it_isnt_so # => "All your base are belong to us." say_it_isnt_so true # => "All's fine!"
    11. 11. Return def do_complicated_stuff(take_shortcut) if take_shortcut return 42 end do_really_complicated_stuff end
    12. 12. Numbers 1 + 1 # => 2 1 + 1.1 # => 2.1 6 * 7 # => 42 6 ** 7 # => 279936 Math.sqrt(65536) # => 256.0 1.class # => Fixnum (2 ** 42).class # => Fixnum (2 ** 64).class # => Bignum 1.1.class # => Float
    13. 13. 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] # => 3 a[1..2] # => [2, 3]
    14. 14. Arrays a = [1,2,3] # => [1, 2, 3] a.push 4 # => ["one", 2, 3, 4] a.pop # => 4 a # => ["one", 2, 3] [1,2,3] | [2, 4] # => [1, 2, 3, 4] [1,2,3] & [2, 4] # => [2]
    15. 15. 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"]
    16. 16. Fun  with  arrays  &  hashes def do_stuff(options = {}) puts options[:hello] if options.include?(:hello) end do_stuff # => nil do_stuff :hello => "hi" # hi # => nil
    17. 17. 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"]
    18. 18. Control  structures if condition # ... elsif other_condition # ... end unless condition # ... end while # ... end
    19. 19. 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
    20. 20. Control  structures puts "How are you gentlemen!!" if role.cats? puts "mommy!" while reaction_from_mommy.nil?
    21. 21. class Pet Classes attr_accessor :name def initialize(name) @name = name end def sit! puts "Wuff" end end fido = Pet.new("fido") # => #<Pet:0x10116e908 @name="fido"> fido.name # => "fido" fido.sit! # => "Wuff"
    22. 22. Classes class Cat < Pet def sit! if rand(10) > 8 # decide our mood super else puts "No way!" end end end mimi = Cat.new("mimi") # => #<Cat:0x101131d00 @name="mimi"> mimi.sit! # => "No way!"
    23. 23. Classes class Cat def self.purr puts "Huh, what? I'm the class!" end def purr puts "prrrrrrr" end end Cat.purr # "Huh, what? I'm the class!" Cat.new("mimi").purr # prrrrrrr
    24. 24. Classes class Fixnum def even? return false if eql? 2 super end end 2.even? # => false 4.even? # => true
    25. 25. Modules module ThingsDoer def do_one_thing puts "doing one thing" end end ThingsDoer::do_one_thing # "doing one thing" # Modules can be used to group methods, classes or other modules
    26. 26. Modules class Pet include ThingsDoer end # we had a Pet instance of fido fido.do_one_thing # "doing one thing"
    27. 27. Naming  convenDons CamelCased # Classes, modules with_underscores # methods, local variables @instance_variable @@class_variable $GLOBAL_VARIABLE
    28. 28. 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 end end do_random_nr_of_times { puts "bla" } # bla # bla # bla # => 1..3
    29. 29. Code  blocks def run value = "bla" do_random_nr_of_times { puts value } end run # bla # bla # => 1..2
    30. 30. Code  blocks the_time = Time.now # Sun Nov 29 20:15:47 0100 2009 the_time # Sun Nov 29 20:15:47 0100 2009 the_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 2009 the_time.call # Sun Nov 29 20:18:20 0100 2009
    31. 31. OpDonal  language  elements def my_method(data, options = {}) # ... end # Full signature my_method("bla", {:option => 'value', :two => 2}) # The last parameter a hash? implicit. my_method("bla", :option => 'value', :two => 2) # Parentheses are optional my_method "bla", :option => 'value', :two => 2 # As long as its unambiguous, it's OK
    32. 32. Regular  expressions s = "Ruby rules" # => "Ruby rules" s =~ /rules/ # => 5 s.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"
    33. 33. ExcepDons begin raise "Someone set us up the bomb." rescue => e puts e.inspect end # <RuntimeError: Someone set us up the bomb.> begin raise StandardError.new("For great justice.") rescue StandardError puts "standard" rescue RuntimeError puts "runtime" end # standard
    34. 34. What’s  more? • No  threading  (at  least,  by  default) • Only  false  and  nil  are  not  true def my_method(my_object) puts my_object && my_object.to_s end my_method(1) # => 1 my_method(nil) # => nil h[:bla] ||= "bla"
    35. 35. Tools
    36. 36. irb
    37. 37. Textmate
    38. 38. What  haven’t  I  talked  about? • TesNng • RSpec • DocumentaNon • RDoc
    39. 39. What  haven’t  I  talked  about? • Gems • Like  ‘apt’  for  ruby • Deployment • SVN • Capistrano
    40. 40. 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..5000 end BlogPost.new(:title -> "My first blog", :body => "is way too short.")
    41. 41. What  haven’t  I  talked  about? • Ruby  on  Rails • Web  framework • Strict  MVC  separaNon • Handles  persistence http://pragprog.com/ titles/rails2
    42. 42. 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'} end end
    43. 43. thank_audience :speaker => 'Angelo vd Sijpt', :greeting => 'You were awesome!', :find_more_at ['ruby-lang.org', 'rubyists.eu']

    ×