SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Similaire à Ruby singleton class

Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
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)lazyatom
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingThaichor Seng
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby evalNiranjan Sarade
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101Nando Vieira
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
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 DornellesTchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingNando Vieira
 
Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)lazyatom
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Bruce Li
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 

Similaire à 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
 

Dernier

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Dernier (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

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

Notes de l'éditeur

  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