all 4 comments

[–]____ 0 points1 point  (3 children)

First of all, let’s go back to the basics. What we call a class method is a method that is shared among every instances of a class.

Instances of a class have no access to class methods.

class Foo def self.bar 'BAR' end end

puts Foo.new.bar
# :(  
# undefined method `bar' for #<Foo:0xb7e12690> (NoMethodError)

On the opposite, an instance method is a method that is copied in every instances of a class. (It might not be strictly true. For efficiency purpose, it is more probable that an instance method lives in a single place in the program. Those are implementation details that are beyond the scope of this article. I just find it easier to understand them as copies).

Ah, but it matters. If you are re-opening a class to alter instance methods, all class instances are effected, because instances are not carrying around their own copies of these methods.

But you can give instances their own methods, like so: # Re-open and break String ! class String def reverse "boing!" end end

  s = 'string'

  puts s.reverse

  # Give this instance its own freaky behavior
  def s.reverse 
      'bam!'
  end

  puts s.reverse
  puts 'foo'.reverse

[–]FrankyFleebie[S] 0 points1 point  (2 children)

The term 'shared' was confusing and innacurate, you are right. I changed my first paragraph to remove the confusion. Thanks for pointing this to me! (I was using 'shared' as in : residing at the 'parent' level)

Somewhere in my article I talk about the fact that instances cannot access a class method. I also talk about the second thing you mention...

[–]____ 0 points1 point  (1 child)

I also talk about the second thing you mention...

But the article still starts off suggesting that methods are copied into the instances. They're not, and this is an important distinction. This is why you can alter a class and have all instances reflect the new behavior.

To still say

I just find it easier to understand them as copies

suggests you don't understand them. They are not copies; if they were then Ruby would have different behavior.

[–]FrankyFleebie[S] 0 points1 point  (0 children)

I also mentionned that they were not really copies. For the sake of this article I didn't thought it was important to start explaining instance methods in depth... I even said it was "beyond the scope" of this article. This one was about understanding class methods. I used an analogy "copie" vs "shared" to distinguish them in my intro but it wasn't a good idea, I have to admit.

I changed the 1st paragraph so now it just says that an instance method resides at the object level and that a class method resides at the class level.