peeyush singla
peeyush singla

Reputation: 577

Ruby's dup and clone method for Class methods

I have read a couple of questions about Ruby dup and clone method Ruby dup and clone. I understand that dup doesn't copy the singleton methods and clone does for any object.

I am trying to check w.r.t class methods but found it bit confusing:-

class User
  def self.active
   'all active users'
  end
end

DupUser = User.dup
DupUser.active #=> all active users'

CloneUser = User.clone
CloneUser.active #=> all active users'

As far as I know, class methods are just singleton methods too, then why does User.dup copied the active method i.e actually a singleton method of User.

Upvotes: 0

Views: 514

Answers (1)

Aaron Breckenridge
Aaron Breckenridge

Reputation: 1819

By design, singleton methods are retained when dup is called on a Class or Module, which is what you're doing in your example. When you dup an instance, singleton methods are not retained:

user = User.new

# This is a singleton method on an Object
def user.active
  'all active users'
end

cloned_user = user.clone
cloned_user.active # => 'all active users'

duped_user = user.dup
duped_user.active # => undefined method `active' for #<User:0x00007fee1f89ae30> (NoMethodError)

Notes

  • def object.method behaves the same as object.extend(module). Methods from module are not duped (with the same caveat for calling dup on Classes or Modules).
  • dup and clone internally call initialize_copy, so that's a starting point for finding how a Class overrides dup or clone.
  • Later versions of ruby added initialize_clone and initialize_dup to fine tune overrides of clone and dup.

Upvotes: 3

Related Questions