SlideShare una empresa de Scribd logo
1 de 16
Ruby methods
Featuring: cats
public class Cat {
public static int getNumLegs() {
return 4;
}
public void eat() {
System.out.println("om nom nom");
}
public static void main(String[] args) {
Cat happyCat = new Cat();
happyCat.eat();
}
}
class Cat
def self.number_of_paws # identity crisis
4
end
end
class Cat; end
happy_cat = Cat.new
def happy_cat.bark
puts "woof"
end
happy_cat.bark
# woof
class Cat; end
happy_cat = Cat.new
class << happy_cat
def bark
puts "woof"
end
end
class SomeClass
class << self
def class_method_1
end
def class_method_2
end
end
end
class Cat
def self.number_of_paws
4
end
end
module CatStuff
def eat
puts "eating the cat way"
end
end
class Cat
include CatStuff
end
module CatClassStuff
def num_of_legs
4
end
end
class Cat
extend CatClassStuff
end
module CatStuff
def bark
puts "woof"
end
end
class Cat; end
happy_cat.include(CatStuff)
module CatStuff
def bark
puts "woof"
end
end
class Cat; end
happy_cat.extend(CatStuff)
happy_cat.bark
# woof
class C; end
C.class_eval do
def d
puts "d"
end
end
C.d
C.new.d
class C; end
C.instance_eval do
def d
puts "d"
end
end
C.d
C.new.d

Más contenido relacionado

Destacado

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
 

Destacado (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 brownbag Yesware Oct 2014

Notas del editor

  1. since this is a talk about ruby, what better way to start than...
  2. # okay, if your first language was Java like mine was, you know what a class method is and what an instance method is. Class or static methods are called on the class, instance methods are called on instances. A method can be either class or instance but not both. Well, Ruby went and turned that upside down. I'm sure you've been told 100 times that everything in Ruby is an object, and that goes for classes too. They're instances of the class Class. That's easy enough to follow until someone goes, so is a method defined on a class a class method or an instance method?
  3. # so you see, if you think of class and instance methods as a dichotomy, you'll get lost pretty quickly. they're not mutually exclusive in Ruby; class methods are a subset of instance methods. so how are class methods different? the difference is that while instance methods apply to all instances of the class they're defined on, class methods only apply to the instance of the class Class that they're defined on. wait what? say that again? it turns out that yes, you can define classes on a single instance of a class, a single object, and only that object would have that method. But since every method needs to belong to a class, ruby calls that class the object's singleton class. basically, every object in Ruby walks around with this singleton class shadowing it. thanks to singleton classes, you can do things like this:
  4. # doing this does not affect the general cat species # which btw you can also do like this
  5. # this angled brackets syntax opens up a new scope where the 'self' object becomes happy_cat inside the block. # you've probably seen the angled brackets syntax used like this
  6. remember those weird class methods? Remember how classes are just instances of the class Class? now you know how it's done.
  7. # self is Cat, so you're defining this method on Cat only now that we know about singleton classes, i want to add a note about how ruby resolves redefined methods.
  8. also note that the way ruby's method resolution works is that each time you redefine a method, it gets inserted into the method lookup chain such that methods defined on singleton classes will resolve first, followed by included modules from bottom to top (i think of it as the methods overwriting each other), and finally the superclass. and as you may have also heard, when it comes to code reuse, rubyists prefer mixins to subclassing, so when you're reading code and something calls 'super' it's actually more likely to go to an included module than a superclass. # now armed with our knowledge of singleton classes, we come to an area that has stirred up much confusion. you know modules can be added to classes with include and extend. but how are they different?
  9. # You may also have seen modules being extended
  10. # The oft cited distinction is that 'include creates instance methods, extend create class methods'. okay, so if i wanted a particular cat to bark, since i'm defining an instance method, i'd do this right?
  11. # guess what that gives us
  12. apparently include isn't an Object method. but if you do this on the other hand
  13. a quick check with the ruby api confirms that
  14. extend is an Object method
  15. whereas include is a Module method and so can only be called on module and classes (which are subclasses of Module). things become clearer if we ditch the class method/instance method distinction and only differentiate methods based on whether they belong to singleton or regular classes (which conveniently is how the creators of Ruby see things). so, include is defined on modules and classes and creates regular-class methods, whereas extend is defined on all objects and creates singleton, object-level methods. looking at things this way also helps with distinguishing between another pair of confusing methods, class_eval and instance_eval. Both take a block of code and execute it.
  16. an uninitiated person would assume class_eval creates class methods and instance_eval creates instance methods. but the present company know that as far as the creators of ruby are concerned, there's no such thing as a class method. but guess what sort of thing class_eval is defined on? that's right, classes. and what sort of thing is instance_eval defined on? instances of classes, also known as objects. those methods are named after their receivers and the context they run the block in, not what they create. so with that in mind, let’s walk through both of these chunks of code. the one on the left evaluates d in the context of the class C, so d should end up being an instance method. so C.d should raise a no method error and c.new.d should print d. the one on the right evaluates d in the context of the object C, so d should be a singleton method that only belongs to C, so C.d should print d and C.new.d should raise a no method error. let’s try it out (remember to kill irb between runs) that concludes my rambling talk. i hope i’ve made the way method definitions work in ruby a little clearer to you.