SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
Ruby




       The Fun Bits
            Matthew Bennett
              @undecisive
          matt@wearepandr.com
And you are...



       Audience
      Participation
Ruby is...




                    Orthogonal
                    Functional
                    Extensible
                    Intuitive
                    Sugary
                    Fun
                    Simple
                    Explorable
                    Expressive
                    Performant
                    Documented
 Object Oriented
 Duck Typed
 Open Source
 Interpreted




                   Are you actually
                     Reading this
 Cross Platform




                     Japaneasey
                      Interesting
                      Web scale
                       Readable




                      Utter tosh
                       Unicorns
 Garbage collected




                        Caring
                         Social




                         Code
 Succinct
 Flexible
 Expressive
 Semicolon-free (if you wish)
levitating Happycat
Terminology



 IRB    Interactive Ruby


 Gems   Libraries / Packages
Terminology

 Duck typing


 Object orientation



 Translation:
  Coding like a HUMAN
CS101: Classes / Objects
Classes != objects

 class Cookie
   def sugary_high
       “Woot”
   end
 end


 kitten = Cookie.new
 kitten.sugary_high    #=> “Woot”
But classes are objects

Cookie = Class.new do
  def sugary_high
      “Woot”
  end
end


kitten = Cookie.new
kitten.sugary_high    #=> “Woot”
Traditional stylee


 if one == :boring_sod
   “Old Skewl”
 else
   “Badass”
 end
What if...
The good stuff
 feel_the_awesome!    if can_i_handle_it?




Ruled by
convention
(ignorable)   Shiny inline if
                                No more is_x()
Failing to not be un-negated




             use_ruby unless self.mad?



  (Note: If you ever show me code with unless...else, I will kill you.)
True Object Orientation
 0.9.round                   #=> 1


 “Groinal attachment”.reverse #=> "tnemhcatta laniorG"

 100.times do
    puts “I am a fish”
 end
 (P.S: Sorry if you are missing Red Dwarf for this rubbish presentation)
Rescue me!

 def something.fail
   raise “The kitten is falling out of the tree”
   something_that_will_never_happen
 end



 something.fail rescue “My hero!”
Gratuitous Cat
Classics
 class Kitten < Moggy
   attr_accessor :cuteness_score


   def initialize
       @cuteness_score = 100000000
   end
 end


 kitty = Kitten.new
 kitten.cuteness_score      #=> 100000000
Classics
 class Kitten < Moggy
   attr_accessor :cuteness_score


   def initialize
       @cuteness_score = 99E99
   end
 end


 kitty = Kitten.new
 kitten.cuteness_score       #=> 99E99
Classics
 class Kitten < Moggy
   attr_accessor :cuteness_score


   def initialize
       @cuteness_score = “WTF”
   end
 end


 kitty = Kitten.new
 kitten.cuteness_score       #=> “WTF”
Classics
 class Kitten < Moggy
   attr_accessor :cuteness_score
 end


 kitty = Kitten.new
 kitty.cuteness_score = :cuter_than_10_kitties


 kitten.cuteness_score=(:cuter_than_10_kitties)
Classics
                              at
 class Kitten < Moggy            tr_
                                     re
                                       ad
   def cuteness_score                    er
                                               :c
                                                  u
       @cuteness_score                                te
                                                         n   es
                                                                s_
   end                                                            sc
                                                                    or
                                                                      e


   def cuteness_score=(mein_score)




                                                                            e
                                                                            or
                                                                          sc
     @cuteness_score = mein_score




                                                                      s_
                                                                  es
                                                                  n
                                                               te
   end




                                                            u
                                                         :c
 end

                                                  e   r
                                               rit
                                            _ w
                                         tr
                                       at
I can comez wiv?
Hate your fellow developer

 class String
   def to_s
       reverse
   end
 end


 “Fishy”.to_s    #=> “yhsiF”
Spread the (un)love
 module Evil
   def to_s
       super.reverse
   end
 end


 class Object ; include Evil ; end
More funky
 [ Object, String, Fixnum, Array ].each do | klass |
   EEK = klass          # class reopened below must be a constants,

   class EEK                 # but constants do not have to be constant.
       def to_s
          “I'm gonna eat you little fishy”
       end
   end
 end
                  (irb):81: warning: already initialized constant EEK
                  (irb):81: warning: already initialized constant EEK
                  (irb):81: warning: already initialized constant EEK
Because you are worth it
●   You deserve:
    –   A language that obeys your whims
    –   A language that allows you to do the logically
        impossible
    –   A language that tries desperately to be your friend




                     VOTE RUBY!
Questions?
Q&A
Show us some ruby in IRB!
 irb(main):003:0* puts "Hello Nrug"
 Hello Nrug
 => nil


More examples of class / object, and accessors
irb(main):004:0> class Question
irb(main):005:1>   attr_accessor :title
irb(main):006:1> end
=> nil
irb(main):007:0> q = Question.new
=> #<Question:0x007fd44a947160>
irb(main):008:0> q.title
=> nil
irb(main):009:0> q.title = "Why won't my baby stop drinking rum?"
=> "Why won't my baby stop drinking rum?"
irb(main):010:0> q.title
=> "Why won't my baby stop drinking rum?"
irb(main):011:0> q.title=("Why won't my baby stop drinking rum?")
=> "Why won't my baby stop drinking rum?"
irb(main):012:0> q.title=("Why won't my baby stop drinking rum?").reverse
=> "?mur gniknird pots ybab ym t'now yhW"
irb(main):013:0> q.title=("Why won't my baby stop drinking rum?").split('
').reverse.join(' ')
=> "rum? drinking stop baby my won't Why"
More Q&A
How would you do a traditional rescue?
   # This is the full syntax
irb(main):014:0> def funny
irb(main):015:1>         begin
irb(main):016:2*            10 / 0
irb(main):017:2>          rescue
irb(main):018:2>             "You FOOL!"
irb(main):019:2>          end
irb(main):020:1> end
=> nil
irb(main):021:0> funny
=> "You FOOL!"

    # But if your methods are small enough,
    # begin...end can be implied
irb(main):022:0> def funny
irb(main):023:1>     10 / 0
irb(main):024:1> rescue
irb(main):025:1>       "You FOOL!"
irb(main):026:1> end
=> nil
irb(main):027:0> funny
=> "You FOOL!"
Extra Awesome Q&A
  Here I try to show that you can add methods on objects, not just on classes
irb(main):044:0*   a = "adsihudsbhjdsghjasjh"
irb(main):051:0>   def a.find_j
irb(main):052:1>     self.scan(/j/).count
irb(main):053:1>   end
=> nil
irb(main):054:0>   a.find_j
=> 3
irb(main):055:0>   a

    # Here is a different String. It will not have the method.
=> "adsihudsbhjdsghjasjh"
irb(main):056:0> "ahgakwdhabhmsbd"
=> "ahgakwdhabhmsbd"
irb(main):057:0> "ahgakwdhabhmsbd".find_j
NoMethodError: undefined method `find_j' for "ahgakwdhabhmsbd":String
    from (irb):57
    from /Users/matthew/.rbenv/versions/1.9.3-p194/bin/irb:12:in
`<main>'
Q&A For Fun And Profit
Question: I hear programmers complaining a lot about badly commented code,
and keeping comments up to date. How does Ruby mitigate this?

Answer: The ruby community drives certain standards. One of these is a
convention for very short methods and descriptive method names:

irb(main):028:0> def destroy_the_world_with_my_massive_laser
irb(main):029:1> start_laser
irb(main):030:1> destroy_world
irb(main):031:1> have_cocktails
irb(main):032:1> end

 When code looks like this, the only reason to add comments is to document
 your gem for people who can't be bothered to look through the code.

 Another question asked: What tools can you use in ruby to ensure conventions
 are followed?

 Answer: I have a large bamboo stick that works really well. For a serious
 answer, there is ruby support in IDEs such as Netbeans and Eclipse, but these
 are rarely faultless. Peer pressure is by far the easiest and most reliable tool.
Rocking that Q&A
Now I show that it's not just methods that return their final value – classes do too...
irb(main):062:0* class Kitty
irb(main):063:1>   self
irb(main):064:1> end
=> Kitty
irb(main):065:0> class Kitty
irb(main):066:1>   "hi"
irb(main):067:1> end
=> "hi"
    # Question: When do I use @@varname – Answer: Never!
    # We can make use of “self” and the fact that you can create
    # methods on objects, and that classes are also objects...
irb(main):068:0> class Kitty
irb(main):069:1>   def self.leg_count
irb(main):070:2>      4
irb(main):071:2>   end
irb(main):072:1> end
=> nil
irb(main):073:0> class Kitty
irb(main):074:1>   def self.leg_count
irb(main):075:2>      @leg_count      # Class-level variables!
irb(main):076:2>     end
irb(main):077:1> end
=> nil
   # @@varname has some odd side effects. It is rarely needed.
And now for the finale
Finally, using a handy trick involving reopening classes, and the value of “self”,
we can create getters and setters on the class level
  irb(main):090:0> class Kitty
  irb(main):091:1>   class << self
  irb(main):092:2>     attr_accessor :leg_count
  irb(main):093:2>   end
  irb(main):094:1> end
  => nil
  irb(main):095:0> Kitty.leg_count = 4000
  => 4000
Final notes:
Unlike certain compiled languages, class definitions are essentially just code. They
get evaluated line by line, so a “puts” statement in a class gets called as the class is
being set up.

If anyone has any questions, or bits of code that they can't get to work for love nor
money, by all means send me a gist. My twitter username is @undecisive.

Ruby is a wonderful language, and you have to try quite hard to find its limits.
http://www.confreaks.com/ Have hundreds of awesome presentations on ruby for free.
Check them out!

Mais conteúdo relacionado

Semelhante a Ruby The Fun Bits

Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
Harkamal Singh
 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpack
David Lowe
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
mbeizer
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
Wen-Tien Chang
 

Semelhante a Ruby The Fun Bits (20)

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
Regular Expressions: Backtracking, and The Little Engine that Could(n't)?
 
Threequals - Case Equality in Ruby
Threequals - Case Equality in RubyThreequals - Case Equality in Ruby
Threequals - Case Equality in Ruby
 
Language supports it
Language supports itLanguage supports it
Language supports it
 
Decyphering Rails 3
Decyphering Rails 3Decyphering Rails 3
Decyphering Rails 3
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured ExceptionsCode Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
 
Ruby Style Guide
Ruby Style GuideRuby Style Guide
Ruby Style Guide
 
Rubinius - A Tool of the Future
Rubinius - A Tool of the FutureRubinius - A Tool of the Future
Rubinius - A Tool of the Future
 
identifica y usa las propiedades de lo exponenentes
identifica y usa las propiedades de lo exponenentesidentifica y usa las propiedades de lo exponenentes
identifica y usa las propiedades de lo exponenentes
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpack
 
Learning Ruby
Learning RubyLearning Ruby
Learning Ruby
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Learning To Walk In Shoes
Learning To Walk In ShoesLearning To Walk In Shoes
Learning To Walk In Shoes
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
A Whirlwind Tour of Perl
A Whirlwind Tour of PerlA Whirlwind Tour of Perl
A Whirlwind Tour of Perl
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Ruby The Fun Bits

  • 1. Ruby The Fun Bits Matthew Bennett @undecisive matt@wearepandr.com
  • 2. And you are... Audience Participation
  • 3. Ruby is... Orthogonal Functional Extensible Intuitive Sugary Fun Simple Explorable Expressive Performant Documented Object Oriented Duck Typed Open Source Interpreted Are you actually Reading this Cross Platform Japaneasey Interesting Web scale Readable Utter tosh Unicorns Garbage collected Caring Social Code Succinct Flexible Expressive Semicolon-free (if you wish)
  • 5. Terminology IRB Interactive Ruby Gems Libraries / Packages
  • 6. Terminology Duck typing Object orientation Translation: Coding like a HUMAN
  • 8. Classes != objects class Cookie def sugary_high “Woot” end end kitten = Cookie.new kitten.sugary_high #=> “Woot”
  • 9. But classes are objects Cookie = Class.new do def sugary_high “Woot” end end kitten = Cookie.new kitten.sugary_high #=> “Woot”
  • 10. Traditional stylee if one == :boring_sod “Old Skewl” else “Badass” end
  • 12. The good stuff feel_the_awesome! if can_i_handle_it? Ruled by convention (ignorable) Shiny inline if No more is_x()
  • 13. Failing to not be un-negated use_ruby unless self.mad? (Note: If you ever show me code with unless...else, I will kill you.)
  • 14. True Object Orientation 0.9.round #=> 1 “Groinal attachment”.reverse #=> "tnemhcatta laniorG" 100.times do puts “I am a fish” end (P.S: Sorry if you are missing Red Dwarf for this rubbish presentation)
  • 15. Rescue me! def something.fail raise “The kitten is falling out of the tree” something_that_will_never_happen end something.fail rescue “My hero!”
  • 17. Classics class Kitten < Moggy attr_accessor :cuteness_score def initialize @cuteness_score = 100000000 end end kitty = Kitten.new kitten.cuteness_score #=> 100000000
  • 18. Classics class Kitten < Moggy attr_accessor :cuteness_score def initialize @cuteness_score = 99E99 end end kitty = Kitten.new kitten.cuteness_score #=> 99E99
  • 19. Classics class Kitten < Moggy attr_accessor :cuteness_score def initialize @cuteness_score = “WTF” end end kitty = Kitten.new kitten.cuteness_score #=> “WTF”
  • 20. Classics class Kitten < Moggy attr_accessor :cuteness_score end kitty = Kitten.new kitty.cuteness_score = :cuter_than_10_kitties kitten.cuteness_score=(:cuter_than_10_kitties)
  • 21. Classics at class Kitten < Moggy tr_ re ad def cuteness_score er :c u @cuteness_score te n es s_ end sc or e def cuteness_score=(mein_score) e or sc @cuteness_score = mein_score s_ es n te end u :c end e r rit _ w tr at
  • 22. I can comez wiv?
  • 23. Hate your fellow developer class String def to_s reverse end end “Fishy”.to_s #=> “yhsiF”
  • 24. Spread the (un)love module Evil def to_s super.reverse end end class Object ; include Evil ; end
  • 25. More funky [ Object, String, Fixnum, Array ].each do | klass | EEK = klass # class reopened below must be a constants, class EEK # but constants do not have to be constant. def to_s “I'm gonna eat you little fishy” end end end (irb):81: warning: already initialized constant EEK (irb):81: warning: already initialized constant EEK (irb):81: warning: already initialized constant EEK
  • 26. Because you are worth it ● You deserve: – A language that obeys your whims – A language that allows you to do the logically impossible – A language that tries desperately to be your friend VOTE RUBY!
  • 28. Q&A Show us some ruby in IRB! irb(main):003:0* puts "Hello Nrug" Hello Nrug => nil More examples of class / object, and accessors irb(main):004:0> class Question irb(main):005:1> attr_accessor :title irb(main):006:1> end => nil irb(main):007:0> q = Question.new => #<Question:0x007fd44a947160> irb(main):008:0> q.title => nil irb(main):009:0> q.title = "Why won't my baby stop drinking rum?" => "Why won't my baby stop drinking rum?" irb(main):010:0> q.title => "Why won't my baby stop drinking rum?" irb(main):011:0> q.title=("Why won't my baby stop drinking rum?") => "Why won't my baby stop drinking rum?" irb(main):012:0> q.title=("Why won't my baby stop drinking rum?").reverse => "?mur gniknird pots ybab ym t'now yhW" irb(main):013:0> q.title=("Why won't my baby stop drinking rum?").split(' ').reverse.join(' ') => "rum? drinking stop baby my won't Why"
  • 29. More Q&A How would you do a traditional rescue? # This is the full syntax irb(main):014:0> def funny irb(main):015:1> begin irb(main):016:2* 10 / 0 irb(main):017:2> rescue irb(main):018:2> "You FOOL!" irb(main):019:2> end irb(main):020:1> end => nil irb(main):021:0> funny => "You FOOL!" # But if your methods are small enough, # begin...end can be implied irb(main):022:0> def funny irb(main):023:1> 10 / 0 irb(main):024:1> rescue irb(main):025:1> "You FOOL!" irb(main):026:1> end => nil irb(main):027:0> funny => "You FOOL!"
  • 30. Extra Awesome Q&A Here I try to show that you can add methods on objects, not just on classes irb(main):044:0* a = "adsihudsbhjdsghjasjh" irb(main):051:0> def a.find_j irb(main):052:1> self.scan(/j/).count irb(main):053:1> end => nil irb(main):054:0> a.find_j => 3 irb(main):055:0> a # Here is a different String. It will not have the method. => "adsihudsbhjdsghjasjh" irb(main):056:0> "ahgakwdhabhmsbd" => "ahgakwdhabhmsbd" irb(main):057:0> "ahgakwdhabhmsbd".find_j NoMethodError: undefined method `find_j' for "ahgakwdhabhmsbd":String from (irb):57 from /Users/matthew/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>'
  • 31. Q&A For Fun And Profit Question: I hear programmers complaining a lot about badly commented code, and keeping comments up to date. How does Ruby mitigate this? Answer: The ruby community drives certain standards. One of these is a convention for very short methods and descriptive method names: irb(main):028:0> def destroy_the_world_with_my_massive_laser irb(main):029:1> start_laser irb(main):030:1> destroy_world irb(main):031:1> have_cocktails irb(main):032:1> end When code looks like this, the only reason to add comments is to document your gem for people who can't be bothered to look through the code. Another question asked: What tools can you use in ruby to ensure conventions are followed? Answer: I have a large bamboo stick that works really well. For a serious answer, there is ruby support in IDEs such as Netbeans and Eclipse, but these are rarely faultless. Peer pressure is by far the easiest and most reliable tool.
  • 32. Rocking that Q&A Now I show that it's not just methods that return their final value – classes do too... irb(main):062:0* class Kitty irb(main):063:1> self irb(main):064:1> end => Kitty irb(main):065:0> class Kitty irb(main):066:1> "hi" irb(main):067:1> end => "hi" # Question: When do I use @@varname – Answer: Never! # We can make use of “self” and the fact that you can create # methods on objects, and that classes are also objects... irb(main):068:0> class Kitty irb(main):069:1> def self.leg_count irb(main):070:2> 4 irb(main):071:2> end irb(main):072:1> end => nil irb(main):073:0> class Kitty irb(main):074:1> def self.leg_count irb(main):075:2> @leg_count # Class-level variables! irb(main):076:2> end irb(main):077:1> end => nil # @@varname has some odd side effects. It is rarely needed.
  • 33. And now for the finale Finally, using a handy trick involving reopening classes, and the value of “self”, we can create getters and setters on the class level irb(main):090:0> class Kitty irb(main):091:1> class << self irb(main):092:2> attr_accessor :leg_count irb(main):093:2> end irb(main):094:1> end => nil irb(main):095:0> Kitty.leg_count = 4000 => 4000 Final notes: Unlike certain compiled languages, class definitions are essentially just code. They get evaluated line by line, so a “puts” statement in a class gets called as the class is being set up. If anyone has any questions, or bits of code that they can't get to work for love nor money, by all means send me a gist. My twitter username is @undecisive. Ruby is a wonderful language, and you have to try quite hard to find its limits. http://www.confreaks.com/ Have hundreds of awesome presentations on ruby for free. Check them out!