SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Ruby’s Singleton Class
You can define methods for a single instance

a = Array.new
b = Array.new

def a.hello
  puts "Hello Devclub!"
end

a.hello
# => "Hello Devclub!"

b.hello
# => NoMethodError: undefined method 'hello' for []:Array
Or override a method on a single instance
class Dog
  def speak
    puts "bark"
  end
end

muki = Dog.new

def muki.speak
  puts "auh"
end

muki.speak
# => "auh"

puff = Dog.new

puff.speak
# => "bark"
Enters the Singleton class

                            class
                  puff                     Dog




          class               muki         super         super
muki                                               Dog
                         Singleton class




muki.singleton_methods
# => ["speak"]

puff.singleton_methods
# => []
class A

  def self.hello
    puts "Hello from class method!"
  end

end



A.hello
# => "Hello from class method!"

A.singleton_methods
# => ["hello"]
A.class
# => Class

A.superclass
# => Object


                      class
               A                     Class




                      super
               A                     Object




                   method dispatch

        A                 'A                  Object
a_meta = class << A; self; end;

puts a_meta
# => #<Class:A>

meta_instance = a_meta.new
# => TypeError: can't create instance of virtual
class
Everything in Ruby is an object

1.class
# => Fixnum

nil.class
# => NilClass

NilClass.class
# => Class

Class.class
# => Class




class A
  puts self.class
end

# => Class
Practical uses



class ApiClient
  attr_accessor :session

  def get_session
    # http request
  end

  def user
    session.user
  end
end
Practical uses

class ApiClientTest < Test::Unit::TestCase

  def setup
    @api_client = ApiClient.new

    def @api_client.get_session
      @api_client.session = Session.new(:user => "Mati")
    end
  end

  def test_user_mati
    @api_client.get_session
    assert(@api_client.user == 'Mati')
  end

  def test_user_nil
    assert(@api_client.user.nil?)
  end

end
Questions?
ESTYLE comp
                      LIF           an
                   AL                 y
                 IT
          G
       DI




                                          We are looking for
   the
CA N N E D




                                          Android Developers
     AP




             S
         P




                                          anton@cannedapps.com

Weitere ähnliche Inhalte

Ähnlich wie Ruby singleton class

Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
Nando Vieira
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 

Ähnlich wie Ruby singleton class (20)

Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Language supports it
Language supports itLanguage supports it
Language supports it
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby eval
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Why I choosed Ruby
Why I choosed RubyWhy I choosed Ruby
Why I choosed Ruby
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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
 

Kürzlich hochgeladen (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
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
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Ruby singleton class

  • 2. You can define methods for a single instance a = Array.new b = Array.new def a.hello puts "Hello Devclub!" end a.hello # => "Hello Devclub!" b.hello # => NoMethodError: undefined method 'hello' for []:Array
  • 3. Or override a method on a single instance class Dog def speak puts "bark" end end muki = Dog.new def muki.speak puts "auh" end muki.speak # => "auh" puff = Dog.new puff.speak # => "bark"
  • 4. Enters the Singleton class class puff Dog class muki super super muki Dog Singleton class muki.singleton_methods # => ["speak"] puff.singleton_methods # => []
  • 5. class A def self.hello puts "Hello from class method!" end end A.hello # => "Hello from class method!" A.singleton_methods # => ["hello"]
  • 6. A.class # => Class A.superclass # => Object class A Class super A Object method dispatch A 'A Object
  • 7. a_meta = class << A; self; end; puts a_meta # => #<Class:A> meta_instance = a_meta.new # => TypeError: can't create instance of virtual class
  • 8. Everything in Ruby is an object 1.class # => Fixnum nil.class # => NilClass NilClass.class # => Class Class.class # => Class class A puts self.class end # => Class
  • 9. Practical uses class ApiClient attr_accessor :session def get_session # http request end def user session.user end end
  • 10. Practical uses class ApiClientTest < Test::Unit::TestCase def setup @api_client = ApiClient.new def @api_client.get_session @api_client.session = Session.new(:user => "Mati") end end def test_user_mati @api_client.get_session assert(@api_client.user == 'Mati') end def test_user_nil assert(@api_client.user.nil?) end end
  • 12. ESTYLE comp LIF an AL y IT G DI We are looking for the CA N N E D Android Developers AP S P anton@cannedapps.com

Hinweis der Redaktion

  1. \n
  2. 2 array instantsi, meetod &amp;#x201C;hello&amp;#x201D; defineeritakse ainult instants &amp;#x201C;a&amp;#x201D;-le\n
  3. Siin on j&amp;#xE4;llegi n&amp;#xE4;ha kuidas &amp;#x201C;muki&amp;#x201D; instantsil defineeritakse &amp;#xFC;le meetod &amp;#x201C;speak&amp;#x201D;\n\nStaatilistest keeltest tulenev l&amp;#xE4;henemine reeglina ette, et on olemas klassid milledel defineeritakse meetodid mida selle klassi objektid kasutada saavad.\n\nKuhu antud juhul &amp;#x201C;muki.speak&amp;#x201D; meetod defineeritakse?\n\nKui see definitsioon tehtaks &amp;#x201C;muki&amp;#x201D; klassile milleks on &amp;#x201C;Dog&amp;#x201D; siis peaks &amp;#x201C;speak&amp;#x201D; meetodi defineerimine laienema ka instantsile &amp;#x201C;puff&amp;#x201D;\n\n\n
  4. muki instantsile luuakse Singleton klass sellel hetkel kui Ruby interpreter n&amp;#xE4;eb vajadust instantsi spetsiifiliseks loogikaks\n
  5. Mis tegelikult juhtub klassi meetodi defineerimisel on see, et see meetod defineeritakse samuti klass A singleton klassi\n\nMiks see nii on?\n\n\n\n\n\n\n\n\n\n
  6. Singleton klassi omadused:\n\n1. N&amp;#xE4;htamatu p&amp;#xE4;rinevuse jadas\n2. Singleton klassi ei saa instantiate&amp;#x2019;ida\n\n\n\n\n\n
  7. Singleton klassi omadused:\n\n1. N&amp;#xE4;htamatu p&amp;#xE4;rinevuse jadas\n2. Singleton klassi ei saa instantiate&amp;#x2019;ida\n\nTODO: show inheritance chain\n\n\n\n
  8. 1. Ruby&amp;#x2019;s on k&amp;#xF5;ik objekt\n\n2. Ruby vajab klassimeetodeid kuid toetab ainult instantsimeetodeid.\n\nA on klassi Class subklass. Objekt-orienteeritust silmas pidades peaks objekti A klassimeetod defineeritama tema superklassi. Seda ei saa aga defineerida klassi Class kuna sellisel juhul oleks antud meetod k&amp;#xF5;ikidele objektidele k&amp;#xE4;ttesaadav.\n\nSeega tulenevalt sellest kuidas Ruby method dispatch t&amp;#xF6;&amp;#xF6;tab luuakse objekti A p&amp;#xE4;rinevusejadasse &amp;#x2018;A kus defineeritakse tema klassimeetodid.\n
  9. K&amp;#xF5;ige lihtsam n&amp;#xE4;ide instantsi spetsiifilisest loogikast on Testides meetodite mock&amp;#x2019;imine\n\nLisaks:\nSingleton class on &amp;#xFC;heks talaks mis teeb Ruby&amp;#x2019;st high-level metaprogrammeerimise keele.\nMida see t&amp;#xE4;hendab on see, et see v&amp;#xF5;imaldab koodi kirjutada \nabstraktselt, domeenispetsiifiliselt, lihtsamalt, loogilisemalt\n\n\n\n\n\n
  10. K&amp;#xF5;ige lihtsam n&amp;#xE4;ide instantsi spetsiifilisest loogikast on Testides meetodite mock&amp;#x2019;imine\n\nLisaks:\nSingleton class on &amp;#xFC;heks talaks mis teeb Ruby&amp;#x2019;st high-level metaprogrammeerimise keele.\nMida see t&amp;#xE4;hendab on see, et see v&amp;#xF5;imaldab koodi kirjutada \nabstraktselt, domeenispetsiifiliselt, lihtsamalt, loogilisemalt\n\n\n\n\n\n\n\n\n\n\n
  11. K&amp;#xF5;ige lihtsam n&amp;#xE4;ide instantsi spetsiifilisest loogikast on Testides meetodite mock&amp;#x2019;imine\n\nLisaks:\nSingleton class on &amp;#xFC;heks talaks mis teeb Ruby&amp;#x2019;st high-level metaprogrammeerimise keele.\nMida see t&amp;#xE4;hendab on see, et see v&amp;#xF5;imaldab koodi kirjutada \nabstraktselt, domeenispetsiifiliselt, lihtsamalt, loogilisemalt\n\n\n\n\n\n\n\n\n\n\n
  12. \n