Last active
December 15, 2015 13:48
-
-
Save ejallday/5269468 to your computer and use it in GitHub Desktop.
I'm new at this, but it's my understanding that with classes: the 'name of the class' (Name), 'self' and simply typing 'new' garner the same result. Name and 'self' are receivers and they invoke #new. In the absence of a receiver and simply typing 'new', the method calls whatever the current object is, which happens to be 'self' and or Name. Why…
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
| class Array | |
| def pad!(min_size, value = nil) | |
| if self.length < min_size | |
| self.fill(value, self.length...min_size) | |
| else | |
| return self | |
| end | |
| end | |
| def pad(min_size, value = nil) | |
| self.clone.pad!(min_size, value) | |
| end | |
| end | |
| ########################################## | |
| class Array | |
| def pad!(min_size, value = nil) | |
| if Array.length < min_size # NoMethodError | |
| Array.fill(value, Array.length...min_size) | |
| else | |
| return Array | |
| end | |
| end | |
| def pad(min_size, value = nil) | |
| Array.clone.pad!(min_size, value) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're confusing the class
Arraywith an instance of anArray. They are two different things. Inside an instance method likepadorpad!, the keywordselfrefers to the current instance, which is not the same as the classArray.Try to think of the class as a blueprint, while an instance is one of many different things the blueprint describes...
There's only one
Arrayclass, but there are can be a ton of instances ofArray...a,b, andcare all instances ofArray.