SlideShare a Scribd company logo
1 of 54
Download to read offline
The Well-Grounded
                                  Nuby
                               Advice for Ruby newcomers*

                                    David A. Black
                                      Senior Developer
                                     Cyrus Innovation, Inc.

                                         * and their mentors!




                                                                Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
About me
                     •      Senior Developer at Cyrus Innovation, Inc.
                     •      Rubyist-at-large since 2000 (Pickaxe baby)
                     •      Owner/director of Ruby Power and Light, LLC
                     •      Author of Ruby for Rails (Manning, 2006) and The Well-
                            Grounded Rubyist (Manning, 2009)
                     •      Director of Ruby Central, Inc. (RubyConf, RubyForge,
                            etc.)
                     •      Twitter: @david_a_black, @compleatrubyist
                     •      Ruby learning and history: http://www.ruby-versions.net


                                                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Goals for today
                     • Learn some major common points of
                            confusion, and how to navigate them
                     • Improve your ability to understand Ruby
                            code
                     • Give yourself some tools for reasoning
                            through code as you write it



                                                                  Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
How we'll proceed
                     • Seven major points, with code demos
                      • chosen because they are common
                             stumbling blocks, even among
                             experienced Ruby programmers
                     • Examples of how the seven points can help
                            you understand Ruby
                     • Questions (throughout)
                                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
I.
                         Every expression
                       evaluates to an object

                                          Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
•    Everything is not an object
                            •   if statements aren't
                            •   argument lists aren't
                            •   keywords aren't
                       •    But everything evaluates to an object
                            •   including if statements, method definitions, class
                                definitions




                                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
irb is your friend
                                        >> if 3 > 5
             A failed if statement
                                        >>   "Not reached!"
             returns nil                >> end
                                        => nil


                                        >> puts "Hello!"
              puts returns nil          Hello!
                                        => nil


               Empty class definition    >> class C
               evaluates to nil         >> end
                                        => nil


               Class definition          >> class C
                                        >>   "Some value in a class definition"
               evaluates to the
                                        >> end
               last expression inside   => "Some value in a class definition"
               it




                                                                                  Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
II.
                            It's all about sending
                            messages to objects

                                                Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Messages everywhere...
                     • Post-dot messages are... messages
                      • as in "abc".upcase
                     • Infix and unary operators are (mostly)
                            messages
                     • Square brackets are a message
                     • case statements send messages

                                                           Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Operators are (mostly)
                             messages (methods)
                                This...   ...is really this!

                                3+2           3.+(2)
                                5*3           5.*(3)
                                 a[2]         a.[](2)
                                                               (Except you can't actually call the
                                 +x           x.+@             +@ method this way.)




                                                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Roll your own + logic!
                            class Person
                              attr_accessor :name
                              class Couple
                                def initialize(one, two)
                                  @pair = [one, two]
                                end

                                def to_s
                                  @pair[0].name + " and " + @pair[1].name
                                end
                              end

                              def +(other)                 Adding two people is defined
                                Couple.new(self, other)
                              end
                                                           as returning a Person::Couple
                            end                            object with those two people.

                            john = Person.new
                            john.name = "John"
                            marcia = Person.new
                            marcia.name = "Marcia"

                            couple = john + marcia
                            puts couple

                               John and Marcia




                                                                                           Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Even case statements send
                               messages to objects!
                   This...            ...is really this...             ...which is really this!...

        case some_string        if "abc" === some_string              if "abc".===(some_string)
        when "abc"                # ...                                 # ...
          # ...                 elsif /def/ === some_string           elsif /def/.===(some_string)
        when /def/                # ...                                 # ...
          # ...                 end                                   end
        end

                                Case statements use the === method,
                                aka the case equality operator, to
                                determine a match




                                                                                          Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Roll your own ===!
                                                               Strictly speaking, you
                              class Person
                                attr_accessor :name, :ssn      could just define ==
                                def ===(other)                 here, since === is the
                                  self.ssn == other.ssn        same as == by default.
                                end
                              end                              But defining === itself
                                                               means that you can
                              david = Person.new
                                                               separate "plain" equality
                              david.ssn = "123-45-6789"
                                                               from case equality if you
                              joe = Person.new                 wish to.
                              joe.ssn = "987-65-4321"

                              mystery = david

                              case mystery
                              when joe               # i.e., if joe === mystery
                                puts "It's Joe!"
                              when david             # i.e., if david === mystery
                                puts "It's David!"
                              end

                                It's David!




                                                                                           Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
III.
                     Objects resolve
                  messages into methods

                                    Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
The intelligence of
                                      objects
                     •      Objects do not "have" methods
                            •   they have the intelligence to find methods when
                                required to do so
                     •      Methods are stored in classes and modules
                     •      Every object has a lookup-path consisting of classes
                            and modules
                            •   singleton class
                            •   modules mixed into singleton class
                            •   class
                            •   modules mixed into class
                            •   superclass, etc., all the way up


                                                                          Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
from The Well-Grounded Rubyist, © 2009 Manning Publications

                                                                                          Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            david = Person.new
                            david.name = "David"




                                                    Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            david = Person.new
                            david.name = "David"

                            module Vocal
                              def talk
                                "Hi, my name is #{name}."
                              end
                            end

                            class Person
                              include Vocal
                            end

                            puts david.talk          Hi, my name is David.




                                                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            david = Person.new
                            david.name = "David"

                            module Vocal
                              def talk
                                "Hi, my name is #{name}."
                              end
                            end

                            class Person
                              include Vocal
                            end

                            puts david.talk

                            module Loud
                              def talk
                                super.upcase.chomp('.') + "!!!"
                              end
                            end

                            class Person
                              include Loud
                            end

                            puts david.talk         HI, MY NAME IS DAVID!!!




                                                                              Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            david = Person.new
                            david.name = "David"

                            module Vocal
                              def talk
                                "Hi, my name is #{name}."
                              end
                            end

                            class Person
                              include Vocal
                            end

                            puts david.talk

                            module Loud
                              def talk
                                super.upcase.chomp('.') + "!!!"
                              end
                            end

                            class Person
                              include Loud
                            end

                            puts david.talk

                            module Quiet
                              def talk
                                "(((" + super.delete('!').downcase + ".)))"
                              end
                            end

                            david.extend(Quiet)         (((hi, my name is david.)))
                            puts david.talk



                                                                                      Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
IV.
                            Classes and modules
                                 are objects

                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
"The answer to 75% of all questions about Ruby is: Because classes are objects!"

                                                          -- Me




                                                                                           Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Classes and modules as
                          objects
                     •      You can send them messages

                     •      They can be put in arrays, etc.

                     •      They can be assigned to local variables

                     •      They have state (instance variables), just like other objects

                     •      They have some special behaviors (nesting, instantiation,
                            inclusion in lookup path, etc.)

                            •   but in many respects, they are just objects!


                                                                                   Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Seen in the wild...

                            def do_something(class_string)
                              THINGS.each do |thing|
                                str = "#{Object.const_get(class_string)}"
                                str << ".#{thing}_method"
                                eval str
                              end
                            end

                            do_something(an_object.class.name)




                                                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Don't work so hard!

                             def do_something(klass)
                               THINGS.each do |thing|
                                 klass.send("#{thing}_method")
                               end
                             end

                             do_something(an_object.class)




                                                                 Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Classes are objects
                                         class Person
                                         end
              You can put a class in a
                                         my_class = Person
              local variable!
                                         david = my_class.new

             You can't use it with the   # class my_class    # ERROR!
             class keyword. However...
                                         my_class.class_eval do
                                           def speak
                                             puts "Hi!"
                                           end
                                         end

                                         david.speak    # Hi!




                                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
V.
                    There's always a self


                                      Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
self-centeredness
                    •       self is the default receiver of messages
                    •       self owns instance variables
                            • and, by definition, any instance variable you see
                              belongs to self
                    •       The value of self changes:
                            • in class definition (becomes the class)
                            • in method definition (to object that will call
                              method)
                            • in instance_eval (becomes the receiver)
                            • in class_eval (becomes the class/module)




                                                                          Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
self
                            class Person
                              puts "self in the class definition body: #{self}"

                              def speak
                                puts "Hi! self in the instance method: #{self}"
                              end
                            end

                            puts "self at the top level: #{self}"

                            david = Person.new
                            david.speak

                                 self in the class definition body: Person
                                 self at the top level: main
                                 Hi! self in the instance method: #<Person:0x1281bc>




                                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
self
                            str = "I am a string!"
                            puts "self is: #{self}"
                            str.instance_eval do
                              puts "self is now: #{self}"
                              puts upcase
                            end

                              self is: main
                              self is now: I am a string!
                              I AM A STRING!




                                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
self
                            my_class = Class.new
                            my_class.class_eval do
                              puts "self in class_eval is: #{self}"
                            end

                             self in class_eval is: #<Class:0x12857c>




                                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
VI.
                              Variables contain
                            references to objects

                                              Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
str = "Hi"
                            str2 = str
                            str2 << " there!"
                            puts str



                              Hi there!




                                                Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
array = [1,2,3]
                            array2 = array
                            array2[3] = 4
                            p array



                              [1, 2, 3, 4]




                                              Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
one = "one"
                            array = [one, "Two", "Three"]
                            one.capitalize!
                            puts one
                            p array


                              One
                              ["One", "Two", "Three"]




                                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
str = "Hi"
                                          str2 = str
                       += creates a new   str2 += " there"
                       string object!     puts str



                                            Hi




                                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
def add_bang(string)
                              string << "!"
                            end

                            str = "Hi"
                            add_bang(str)
                            puts str


                               Hi!




                                                   Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
VII.
                  true and false are objects;
                    true and false are states



                                         Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Truth and falsehood
                     •      Every object has a boolean value
                     •      The objects false and nil have a boolean value of
                            false.
                     •      Every other object has a boolean value of true.
                            •   true is true
                            •   0 is true

                            •   "" is true
                            •   [] is true

                                                                              Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
The truth test
                        For any object obj, think of:

                        if obj
                          puts "obj has a boolean value of true"
                        end

                        And remember... every expression evaluates to an object, including class definitions!

                        if class A
                            end
                          puts "True!"
                        end

                        # No output(because the class definition evaluates to nil)


                        if class A
                              0
                            end
                          puts "True!"
                        end

                        # Output: True!(because the class definition evaluates to 0,
                        # which has a boolean value of true)




                                                                                                               Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Summary
                     I. Every expression evaluates to an object
                     II. It's all about sending messages to objects
                     III. Objects resolve messages into methods
                     IV. Classes and modules are objects
                     V. There's always a self
                     VI. Variables contain references to objects
                     VII. true and false are objects; true and false are states


                                                                      Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
Questions so far?



                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
What do these evaluate to,
                             what do they output,
                                   and why?




                                                         Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
10 if false

                            10 if true

                            puts 10 if true

                            if 10 > 3
                              puts "True!"
                            else
                              puts "Not true!"
                            end

                            if 10 > 3
                              "True!"
                            end




                                                 Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Talker
                              @x = 1
                              def talk
                                puts "x is #{@x}"
                              end
                            end

                            t = Talker.new
                            t.talk




                                                    Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Talker
                              def talk
                               @x = 1
                               puts "x is #{@x}"
                              end
                            end

                            t = Talker.new
                            t.talk




                                                   Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class C
                              def talk
                                puts "Hi!"
                              end
                            end




                                             Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class C
                              "Hi!"
                            end




                                      Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class C
                              self
                            end




                                      Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
obj = Object.new
                            class << obj
                              self
                            end




                                               Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            d = Person.new
                            d.name = "David"
                            puts d.name
                            d.instance_eval { puts name }


                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            d = Person.new
                            d.name = "David"
                            puts d.name
                            d.instance_eval { puts @name }


                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
class Person
                              attr_accessor :name
                            end

                            d = Person.new
                            d.name = "David"
                            @name = "Matz"
                            puts d.name
                            d.instance_eval { puts @name }

                                                         Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010
That's all!

                            Enjoy your Ruby literacy!



                            David A. Black
                            Senior Developer
                            Cyrus Innovation, Inc.

                            dblack@rubypal.com

                                                        Copyright © 2010, Ruby Power and Light, LLC


Friday, September 3, 2010

More Related Content

Similar to The Well-Grounded Nuby

Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1Pavel Tyk
 
How to use Ruby in QA, DevOps, Development. Ruby lang Intro
How to use Ruby in QA, DevOps, Development. Ruby lang IntroHow to use Ruby in QA, DevOps, Development. Ruby lang Intro
How to use Ruby in QA, DevOps, Development. Ruby lang IntroViacheslav Horbovskykh
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Thomas Lundström
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010ssoroka
 
JRuby - The Best of Java and Ruby
JRuby - The Best of Java and RubyJRuby - The Best of Java and Ruby
JRuby - The Best of Java and RubyEvgeny Rahman
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Developing Cocoa Applications with macRuby
Developing Cocoa Applications with macRubyDeveloping Cocoa Applications with macRuby
Developing Cocoa Applications with macRubyBrendan Lim
 
Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02sagaroceanic11
 

Similar to The Well-Grounded Nuby (15)

Children of Ruby
Children of RubyChildren of Ruby
Children of Ruby
 
Keeping ruby reasonable
Keeping ruby reasonableKeeping ruby reasonable
Keeping ruby reasonable
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
 
How to use Ruby in QA, DevOps, Development. Ruby lang Intro
How to use Ruby in QA, DevOps, Development. Ruby lang IntroHow to use Ruby in QA, DevOps, Development. Ruby lang Intro
How to use Ruby in QA, DevOps, Development. Ruby lang Intro
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010
 
JRuby - The Best of Java and Ruby
JRuby - The Best of Java and RubyJRuby - The Best of Java and Ruby
JRuby - The Best of Java and Ruby
 
ruby-cocoa
ruby-cocoaruby-cocoa
ruby-cocoa
 
ruby-cocoa
ruby-cocoaruby-cocoa
ruby-cocoa
 
Initiation à Ruby on Rails
Initiation à Ruby on RailsInitiation à Ruby on Rails
Initiation à Ruby on Rails
 
JRuby in The Enterprise
JRuby in The EnterpriseJRuby in The Enterprise
JRuby in The Enterprise
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Developing Cocoa Applications with macRuby
Developing Cocoa Applications with macRubyDeveloping Cocoa Applications with macRuby
Developing Cocoa Applications with macRuby
 
Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02
 

Recently uploaded

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

The Well-Grounded Nuby

  • 1. The Well-Grounded Nuby Advice for Ruby newcomers* David A. Black Senior Developer Cyrus Innovation, Inc. * and their mentors! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 2. About me • Senior Developer at Cyrus Innovation, Inc. • Rubyist-at-large since 2000 (Pickaxe baby) • Owner/director of Ruby Power and Light, LLC • Author of Ruby for Rails (Manning, 2006) and The Well- Grounded Rubyist (Manning, 2009) • Director of Ruby Central, Inc. (RubyConf, RubyForge, etc.) • Twitter: @david_a_black, @compleatrubyist • Ruby learning and history: http://www.ruby-versions.net Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 3. Goals for today • Learn some major common points of confusion, and how to navigate them • Improve your ability to understand Ruby code • Give yourself some tools for reasoning through code as you write it Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 4. How we'll proceed • Seven major points, with code demos • chosen because they are common stumbling blocks, even among experienced Ruby programmers • Examples of how the seven points can help you understand Ruby • Questions (throughout) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 5. I. Every expression evaluates to an object Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 6. Everything is not an object • if statements aren't • argument lists aren't • keywords aren't • But everything evaluates to an object • including if statements, method definitions, class definitions Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 7. irb is your friend >> if 3 > 5 A failed if statement >> "Not reached!" returns nil >> end => nil >> puts "Hello!" puts returns nil Hello! => nil Empty class definition >> class C evaluates to nil >> end => nil Class definition >> class C >> "Some value in a class definition" evaluates to the >> end last expression inside => "Some value in a class definition" it Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 8. II. It's all about sending messages to objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 9. Messages everywhere... • Post-dot messages are... messages • as in "abc".upcase • Infix and unary operators are (mostly) messages • Square brackets are a message • case statements send messages Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 10. Operators are (mostly) messages (methods) This... ...is really this! 3+2 3.+(2) 5*3 5.*(3) a[2] a.[](2) (Except you can't actually call the +x x.+@ +@ method this way.) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 11. Roll your own + logic! class Person attr_accessor :name class Couple def initialize(one, two) @pair = [one, two] end def to_s @pair[0].name + " and " + @pair[1].name end end def +(other) Adding two people is defined Couple.new(self, other) end as returning a Person::Couple end object with those two people. john = Person.new john.name = "John" marcia = Person.new marcia.name = "Marcia" couple = john + marcia puts couple John and Marcia Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 12. Even case statements send messages to objects! This... ...is really this... ...which is really this!... case some_string if "abc" === some_string if "abc".===(some_string) when "abc" # ... # ... # ... elsif /def/ === some_string elsif /def/.===(some_string) when /def/ # ... # ... # ... end end end Case statements use the === method, aka the case equality operator, to determine a match Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 13. Roll your own ===! Strictly speaking, you class Person attr_accessor :name, :ssn could just define == def ===(other) here, since === is the self.ssn == other.ssn same as == by default. end end But defining === itself means that you can david = Person.new separate "plain" equality david.ssn = "123-45-6789" from case equality if you joe = Person.new wish to. joe.ssn = "987-65-4321" mystery = david case mystery when joe # i.e., if joe === mystery puts "It's Joe!" when david # i.e., if david === mystery puts "It's David!" end It's David! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 14. III. Objects resolve messages into methods Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 15. The intelligence of objects • Objects do not "have" methods • they have the intelligence to find methods when required to do so • Methods are stored in classes and modules • Every object has a lookup-path consisting of classes and modules • singleton class • modules mixed into singleton class • class • modules mixed into class • superclass, etc., all the way up Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 16. from The Well-Grounded Rubyist, © 2009 Manning Publications Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 17. class Person attr_accessor :name end david = Person.new david.name = "David" Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 18. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk Hi, my name is David. Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 19. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk module Loud def talk super.upcase.chomp('.') + "!!!" end end class Person include Loud end puts david.talk HI, MY NAME IS DAVID!!! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 20. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk module Loud def talk super.upcase.chomp('.') + "!!!" end end class Person include Loud end puts david.talk module Quiet def talk "(((" + super.delete('!').downcase + ".)))" end end david.extend(Quiet) (((hi, my name is david.))) puts david.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 21. IV. Classes and modules are objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 22. "The answer to 75% of all questions about Ruby is: Because classes are objects!" -- Me Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 23. Classes and modules as objects • You can send them messages • They can be put in arrays, etc. • They can be assigned to local variables • They have state (instance variables), just like other objects • They have some special behaviors (nesting, instantiation, inclusion in lookup path, etc.) • but in many respects, they are just objects! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 24. Seen in the wild... def do_something(class_string) THINGS.each do |thing| str = "#{Object.const_get(class_string)}" str << ".#{thing}_method" eval str end end do_something(an_object.class.name) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 25. Don't work so hard! def do_something(klass) THINGS.each do |thing| klass.send("#{thing}_method") end end do_something(an_object.class) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 26. Classes are objects class Person end You can put a class in a my_class = Person local variable! david = my_class.new You can't use it with the # class my_class # ERROR! class keyword. However... my_class.class_eval do def speak puts "Hi!" end end david.speak # Hi! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 27. V. There's always a self Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 28. self-centeredness • self is the default receiver of messages • self owns instance variables • and, by definition, any instance variable you see belongs to self • The value of self changes: • in class definition (becomes the class) • in method definition (to object that will call method) • in instance_eval (becomes the receiver) • in class_eval (becomes the class/module) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 29. self class Person puts "self in the class definition body: #{self}" def speak puts "Hi! self in the instance method: #{self}" end end puts "self at the top level: #{self}" david = Person.new david.speak self in the class definition body: Person self at the top level: main Hi! self in the instance method: #<Person:0x1281bc> Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 30. self str = "I am a string!" puts "self is: #{self}" str.instance_eval do puts "self is now: #{self}" puts upcase end self is: main self is now: I am a string! I AM A STRING! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 31. self my_class = Class.new my_class.class_eval do puts "self in class_eval is: #{self}" end self in class_eval is: #<Class:0x12857c> Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 32. VI. Variables contain references to objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 33. str = "Hi" str2 = str str2 << " there!" puts str Hi there! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 34. array = [1,2,3] array2 = array array2[3] = 4 p array [1, 2, 3, 4] Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 35. one = "one" array = [one, "Two", "Three"] one.capitalize! puts one p array One ["One", "Two", "Three"] Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 36. str = "Hi" str2 = str += creates a new str2 += " there" string object! puts str Hi Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 37. def add_bang(string) string << "!" end str = "Hi" add_bang(str) puts str Hi! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 38. VII. true and false are objects; true and false are states Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 39. Truth and falsehood • Every object has a boolean value • The objects false and nil have a boolean value of false. • Every other object has a boolean value of true. • true is true • 0 is true • "" is true • [] is true Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 40. The truth test For any object obj, think of: if obj puts "obj has a boolean value of true" end And remember... every expression evaluates to an object, including class definitions! if class A end puts "True!" end # No output(because the class definition evaluates to nil) if class A 0 end puts "True!" end # Output: True!(because the class definition evaluates to 0, # which has a boolean value of true) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 41. Summary I. Every expression evaluates to an object II. It's all about sending messages to objects III. Objects resolve messages into methods IV. Classes and modules are objects V. There's always a self VI. Variables contain references to objects VII. true and false are objects; true and false are states Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 42. Questions so far? Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 43. What do these evaluate to, what do they output, and why? Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 44. 10 if false 10 if true puts 10 if true if 10 > 3 puts "True!" else puts "Not true!" end if 10 > 3 "True!" end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 45. class Talker @x = 1 def talk puts "x is #{@x}" end end t = Talker.new t.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 46. class Talker def talk @x = 1 puts "x is #{@x}" end end t = Talker.new t.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 47. class C def talk puts "Hi!" end end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 48. class C "Hi!" end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 49. class C self end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 50. obj = Object.new class << obj self end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 51. class Person attr_accessor :name end d = Person.new d.name = "David" puts d.name d.instance_eval { puts name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 52. class Person attr_accessor :name end d = Person.new d.name = "David" puts d.name d.instance_eval { puts @name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 53. class Person attr_accessor :name end d = Person.new d.name = "David" @name = "Matz" puts d.name d.instance_eval { puts @name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  • 54. That's all! Enjoy your Ruby literacy! David A. Black Senior Developer Cyrus Innovation, Inc. dblack@rubypal.com Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010