Last active
December 19, 2015 00:49
-
-
Save sansari/5871597 to your computer and use it in GitHub Desktop.
Classes & Objects Review
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Defining a new class | |
| class Student | |
| end | |
| # Creating an instance of a class | |
| > student = Student.new | |
| > student.class | |
| => Student | |
| # Defining an instance method in a class | |
| class Student | |
| def shout | |
| puts "HEY!" | |
| end | |
| end | |
| # Invoking an instance method on a class | |
| > student = Student.new | |
| > student.shout | |
| HEY! | |
| => nil | |
| # Defining an attribute accessor on a class | |
| # NOTE: This creates two methods for us: .name and .name= | |
| class Student | |
| attr_accessor :name | |
| end | |
| > student = Student.new | |
| > student.name | |
| => nil | |
| > student.name = "Salman" | |
| => "Salman" | |
| > student.name | |
| => "Salman" | |
| # Using an attribute in an instance method | |
| class Student | |
| attr_accessor :name | |
| def shout_name | |
| puts "HEY! Its me, #{@name}" | |
| end | |
| end | |
| > student = Student.new | |
| > student.name = "Salman" | |
| => "Salman" | |
| > student.shout_name | |
| HEY! Its me, Salman | |
| => nil | |
| # Defining a CLASS method on a class | |
| class Student | |
| attr_accessor :name | |
| def self.race | |
| "Human" | |
| end | |
| def shout_name | |
| puts "HEY! Its me, #{@name}" | |
| end | |
| end | |
| > student = Student.new | |
| > student.name | |
| => "Salman" | |
| > student.shout_name | |
| HEY! Its me, Salman | |
| => nil | |
| > student.class | |
| => Student | |
| > student.class.race | |
| => "Human" | |
| > Student.race | |
| => "Human" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment