Skip to content

Instantly share code, notes, and snippets.

@ejallday
Last active December 15, 2015 13:48
Show Gist options
  • Select an option

  • Save ejallday/5269468 to your computer and use it in GitHub Desktop.

Select an option

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…
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
@redsquirrel
Copy link

You're confusing the class Array with an instance of an Array. They are two different things. Inside an instance method like pad or pad!, the keyword self refers to the current instance, which is not the same as the class Array.

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 Array class, but there are can be a ton of instances of Array...

a = [1, 3, 5]
b = (53..80).to_a
c = "foo bar".split

a, b, and c are all instances of Array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment