SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
#8
                                “self
                                      ”
                         Ruby



Montag, 20. Februar 12
It’s all about (my) self!




Montag, 20. Februar 12
self


                         self ist ein Schlüsselwort

                         self zeigt immer auf das “aktuelle” Objekt

                         self ist abhängig vom Kontext

                         self ist der Default-Empfänger von Nachrichten




Montag, 20. Februar 12
self ändern


                         self = Object.new




Montag, 20. Februar 12
self ändern


                                  self = Object.new

                                           ;)
                         SyntaxError: Can't change the value of self



Montag, 20. Februar 12
self ändern

                         self ändert sich immer dann, wenn der Kontext sich ändert

                         Und das passiert z.B. bei

                           einem Methodenaufruf

                           einer Klassen oder Modul-Definition

                           bei der Verwendung von instance_eval, class_eval & co




Montag, 20. Februar 12
class Pony
                           def visit(other_pony)
                             puts "#{self} is on a visit."
                             other_pony.is_pleased
                           end

                           def is_pleased
                             puts "#{self} is pleased about a visit."
                           end
                         end

                         Pony.new("Applejack").visit Pony.new("Pinkie Pie")



                         => #<Pony:Applejack> is on a visit.
                         => #<Pony:Pinkie Pie> is pleased about a visit.

Montag, 20. Februar 12
class & module
                           class Pony
                             puts self

                             def work
                               puts self
                             end
                           end

                           => Pony

                           Pony.new.work

                           => #<Pony:0x106da8368>

Montag, 20. Februar 12
class_eval & instance_eval




Montag, 20. Februar 12
class_eval & instance_eval

                         es gibt instance_eval und class_eval / module_eval

                         instance_eval

                          instance_eval lässt sich durch class_eval äquivalent verwenden

                         class_eval / module_eval

                          führt Code (String oder Block) im Kontext des Empfängers aus

                          self wird innerhalb des Blocks auf den Empfänger geändert



Montag, 20. Februar 12
class Pony; end

                         Pony.class_eval do
                           puts self
                           def work
                             puts "#{self} is working!"
                           end
                         end

                         => Pony

                         Pony.new.work

                         => #<Pony:0x10bc98a68> is working!


Montag, 20. Februar 12
class Pony
                           private
                           def age
                             "Don't let anyone know!"
                           end
                         end

                         twilight_sparkle = Pony.new
                         puts twilight_sparkle

                         => #<Pony:0x10ba7b690>

                         twilight_sparkle.instance_eval do
                           puts self
                           puts age
                         end

                         => #<Pony:0x10ba7b690>
                         => Don't let anyone know!
Montag, 20. Februar 12
Fun fact #1

                             private Methoden sind nur mit
                             implizitem Empfänger zulässig!
               class Pony
                 def want_to_know_age!
                   self.age
                 end
                                               Pony.new.want_to_know_age!
                 private
                 def age                       NoMethodError: private method ‘age’
                   "Don't let anyone know!"
                                                              called for #<Pony:0x00…d8>
                 end
               end
Montag, 20. Februar 12
It’s all about methods!




Montag, 20. Februar 12
class Ranking
                           def initialize(items)
                             @items = items
                           end

                           def rank!
                             @items.each do |item|
                               # ... perform a secret ranking here
                             end
                           end

                           def size
                             @item.size
                           end
                                                     ranking = Ranking.new([1,2,3,4])
                           def each(&block)          ranking.rank!
                             @item.each(&block)
                           end
                         end
Montag, 20. Februar 12
Singleton Methods

                         ranking = [1,2,3,4]     Singleton Methods sind Methoden,
                                                 die nur auf einer Objektinstanz
                         def ranking.rank!       definiert sind
                           self.each do |item|
                             # perform ranking   Andere Instanzen der gleichen
                           end                   Klasse, besitzen diese Methode nicht
                         end
                                                 Sie erweitern also eine spezifische
                         ranking.rank!           Objektinstanz




Montag, 20. Februar 12
Benutzt du regelmäßig
                           Singleton Methods?



Montag, 20. Februar 12
Bestimmt!




Montag, 20. Februar 12
Wetten? ;)




Montag, 20. Februar 12
Fun fact #2
                                   Class Methods sind
                                   Singleton Methods!

                 class Ranking              Klassen sind Objekte, von der Klasse Class
                   def self.default_score
                                            Daher besitzen sie ebenfalls Singleton Methods
                     23
                   end                      Man vergleiche...
                 end

                                             def ranking.rank!; … end

                                             def Ranking.default_score
Montag, 20. Februar 12
Methoden in Ruby


                         class Ranking

                          def rank!; end                Methode für Instanzen

                          def self.default_score; end   Methode für self (also Ranking)

                         end




Montag, 20. Februar 12
Ruby Object Model




Montag, 20. Februar 12
Ruby Object Model

                                       BasicObject
                          superclass
                                         Object

                                          User


                                        #<User>


Montag, 20. Februar 12
Ruby Object Model
                                                 BasicObject

                                                   Object
                         superclass




                                                               Module

                                        User                   Class


                                       #<User>

Montag, 20. Februar 12
Was hast das mit self zu
                         tun? Oder mit Methoden?
                         pinkie_pie = Pony.new

                         def pinkie_pie.partey
                           puts "PARTEY!!"
                         end

                         puts   Pony.instance_methods.include? :partey
                         # =>   false
                         puts   pinkie_pie.methods.include? :partey
                         # =>   true


                         Woher kommt #partey?!
Montag, 20. Februar 12
Introducing
                         Singleton Class



Montag, 20. Februar 12
Singleton Class

                         Jedes Objekt hat seine eigene Meta Klasse, oder auch Singleton Class



                         Instanz-Variablen (Zustand) lebt in Objekten/Instanzen

                         Methoden (Verhalten) leben in Klassen/Modulen



                         Daher muss es für jedes Objekt eine eigene Klasse geben!


Montag, 20. Februar 12
Klassen, Singleton Classes,
                                 Objects....?!
                                  User

                                             superclass


                               class                #<Class:#<User:0x2A>>
                                              singleton
                                                class

                              #<User:0x2A>


Montag, 20. Februar 12
Singleton Class explizit
                                 machen
                         singleton_klass = (class << Ranking; self; end)
                         singleton_klass = Ranking.singleton_class # 1.9

                         class Ranking
                           class << self
                             def singleton_class
                               return self
                             end
                           end
                         end


Montag, 20. Februar 12
Methoden finden in Ruby

                                        Object
     class User
       def self.default_location                      Singleton Class von
         "Earth"                    #<Class:User>
       end
                                                         der User Klasse
     end
                                         User
     hubert = User.new

     def hubert.resarch
                                   #<Class:#<User>>   Singleton Class von
       # researching ...
     end
                                                             hubert


                                       #<User>

Montag, 20. Februar 12
Fun Fact #3


                         Ranking.singleton_class.class_eval {}

                                          ==

                               Ranking.instance_eval {}



Montag, 20. Februar 12
self hängt vom Kontext ab

                         Methoden leben in Modulen,
                         Variablen in Objektinstanzen

                         Alle(!) Objektinstanzen haben
                         Singleton Classes




Montag, 20. Februar 12
One More Thing …


Montag, 20. Februar 12
Frage!!



Montag, 20. Februar 12
Was passiert hier?!
                         class MyClass

                          def outer_method
                            puts "outer"

                            def inner_method    NoMethodError: undefined method
                              puts "inner"      `inner_method' for #<Bar:0x00…68>
                            end
                          end

                         end

                         MyClass.new.inner_method
Montag, 20. Februar 12
Was passiert hier?!

                         class MyClass             obj = MyClass.new

                          def outer_method         obj.outer_method
                            puts "outer"           # => outer

                            def inner_method       obj.inner_method
                              puts "inner"         # => inner
                            end
                          end

                         end                   Hint: Was ist self?
Montag, 20. Februar 12
Thanks! Q & A?



                                     ?



                                                                            “My Little Pony” © Hasbro Studios and DHX Media Vancouver
                           Dirk Breuer / @railsbros_dirk

                            Sebastian Cohnen / @tisba

                                                           rubyismagic.de
Montag, 20. Februar 12

Weitere ähnliche Inhalte

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Ruby is Magic - Episode #8: self

  • 1. #8 “self ” Ruby Montag, 20. Februar 12
  • 2. It’s all about (my) self! Montag, 20. Februar 12
  • 3. self self ist ein Schlüsselwort self zeigt immer auf das “aktuelle” Objekt self ist abhängig vom Kontext self ist der Default-Empfänger von Nachrichten Montag, 20. Februar 12
  • 4. self ändern self = Object.new Montag, 20. Februar 12
  • 5. self ändern self = Object.new ;) SyntaxError: Can't change the value of self Montag, 20. Februar 12
  • 6. self ändern self ändert sich immer dann, wenn der Kontext sich ändert Und das passiert z.B. bei einem Methodenaufruf einer Klassen oder Modul-Definition bei der Verwendung von instance_eval, class_eval & co Montag, 20. Februar 12
  • 7. class Pony def visit(other_pony) puts "#{self} is on a visit." other_pony.is_pleased end def is_pleased puts "#{self} is pleased about a visit." end end Pony.new("Applejack").visit Pony.new("Pinkie Pie") => #<Pony:Applejack> is on a visit. => #<Pony:Pinkie Pie> is pleased about a visit. Montag, 20. Februar 12
  • 8. class & module class Pony puts self def work puts self end end => Pony Pony.new.work => #<Pony:0x106da8368> Montag, 20. Februar 12
  • 10. class_eval & instance_eval es gibt instance_eval und class_eval / module_eval instance_eval instance_eval lässt sich durch class_eval äquivalent verwenden class_eval / module_eval führt Code (String oder Block) im Kontext des Empfängers aus self wird innerhalb des Blocks auf den Empfänger geändert Montag, 20. Februar 12
  • 11. class Pony; end Pony.class_eval do puts self def work puts "#{self} is working!" end end => Pony Pony.new.work => #<Pony:0x10bc98a68> is working! Montag, 20. Februar 12
  • 12. class Pony private def age "Don't let anyone know!" end end twilight_sparkle = Pony.new puts twilight_sparkle => #<Pony:0x10ba7b690> twilight_sparkle.instance_eval do puts self puts age end => #<Pony:0x10ba7b690> => Don't let anyone know! Montag, 20. Februar 12
  • 13. Fun fact #1 private Methoden sind nur mit implizitem Empfänger zulässig! class Pony def want_to_know_age! self.age end Pony.new.want_to_know_age! private def age NoMethodError: private method ‘age’ "Don't let anyone know!" called for #<Pony:0x00…d8> end end Montag, 20. Februar 12
  • 14. It’s all about methods! Montag, 20. Februar 12
  • 15. class Ranking def initialize(items) @items = items end def rank! @items.each do |item| # ... perform a secret ranking here end end def size @item.size end ranking = Ranking.new([1,2,3,4]) def each(&block) ranking.rank! @item.each(&block) end end Montag, 20. Februar 12
  • 16. Singleton Methods ranking = [1,2,3,4] Singleton Methods sind Methoden, die nur auf einer Objektinstanz def ranking.rank! definiert sind self.each do |item| # perform ranking Andere Instanzen der gleichen end Klasse, besitzen diese Methode nicht end Sie erweitern also eine spezifische ranking.rank! Objektinstanz Montag, 20. Februar 12
  • 17. Benutzt du regelmäßig Singleton Methods? Montag, 20. Februar 12
  • 20. Fun fact #2 Class Methods sind Singleton Methods! class Ranking Klassen sind Objekte, von der Klasse Class def self.default_score Daher besitzen sie ebenfalls Singleton Methods 23 end Man vergleiche... end def ranking.rank!; … end def Ranking.default_score Montag, 20. Februar 12
  • 21. Methoden in Ruby class Ranking def rank!; end Methode für Instanzen def self.default_score; end Methode für self (also Ranking) end Montag, 20. Februar 12
  • 22. Ruby Object Model Montag, 20. Februar 12
  • 23. Ruby Object Model BasicObject superclass Object User #<User> Montag, 20. Februar 12
  • 24. Ruby Object Model BasicObject Object superclass Module User Class #<User> Montag, 20. Februar 12
  • 25. Was hast das mit self zu tun? Oder mit Methoden? pinkie_pie = Pony.new def pinkie_pie.partey puts "PARTEY!!" end puts Pony.instance_methods.include? :partey # => false puts pinkie_pie.methods.include? :partey # => true Woher kommt #partey?! Montag, 20. Februar 12
  • 26. Introducing Singleton Class Montag, 20. Februar 12
  • 27. Singleton Class Jedes Objekt hat seine eigene Meta Klasse, oder auch Singleton Class Instanz-Variablen (Zustand) lebt in Objekten/Instanzen Methoden (Verhalten) leben in Klassen/Modulen Daher muss es für jedes Objekt eine eigene Klasse geben! Montag, 20. Februar 12
  • 28. Klassen, Singleton Classes, Objects....?! User superclass class #<Class:#<User:0x2A>> singleton class #<User:0x2A> Montag, 20. Februar 12
  • 29. Singleton Class explizit machen singleton_klass = (class << Ranking; self; end) singleton_klass = Ranking.singleton_class # 1.9 class Ranking class << self def singleton_class return self end end end Montag, 20. Februar 12
  • 30. Methoden finden in Ruby Object class User def self.default_location Singleton Class von "Earth" #<Class:User> end der User Klasse end User hubert = User.new def hubert.resarch #<Class:#<User>> Singleton Class von # researching ... end hubert #<User> Montag, 20. Februar 12
  • 31. Fun Fact #3 Ranking.singleton_class.class_eval {} == Ranking.instance_eval {} Montag, 20. Februar 12
  • 32. self hängt vom Kontext ab Methoden leben in Modulen, Variablen in Objektinstanzen Alle(!) Objektinstanzen haben Singleton Classes Montag, 20. Februar 12
  • 33. One More Thing … Montag, 20. Februar 12
  • 35. Was passiert hier?! class MyClass def outer_method puts "outer" def inner_method NoMethodError: undefined method puts "inner" `inner_method' for #<Bar:0x00…68> end end end MyClass.new.inner_method Montag, 20. Februar 12
  • 36. Was passiert hier?! class MyClass obj = MyClass.new def outer_method obj.outer_method puts "outer" # => outer def inner_method obj.inner_method puts "inner" # => inner end end end Hint: Was ist self? Montag, 20. Februar 12
  • 37. Thanks! Q & A? ? “My Little Pony” © Hasbro Studios and DHX Media Vancouver Dirk Breuer / @railsbros_dirk Sebastian Cohnen / @tisba rubyismagic.de Montag, 20. Februar 12