class_eval vs (class << object)

R

Ruby Freak

What is the difference between class_eval and "class << object"?

It seems like they are the same. I am thinking that class_eval affects
the greater class and "class_object" is used on a singleton class. Are
they mutually exclusive?

Thanks
 
7

7stud --

Ruby said:
What is the difference between class_eval and "class << object"?

It seems like they are the same. I am thinking that class_eval affects
the greater class and "class_object" is used on a singleton class. Are
they mutually exclusive?

Thanks

class Dog
attr_accessor :age

def initialize(a)
@age = a
end
end

Dog.class_eval{
def show
puts @age
end
}


d1 = Dog.new(5)
d2 = Dog.new(2)

d1.show #5
d2.show #2


class Dog
attr_accessor :age

def initialize(a)
@age = a
end
end


d1 = Dog.new(5)

class << d1
def show
puts age
end
end

d1.show #5

d2 = Dog.new(2)
d2.show

--output:--
undefined method `show' for #<Dog:0x25260 @age=2> (NoMethodError)
 
7

7stud --

Ruby said:
What is the difference between class_eval and "class << object"?

It seems like they are the same. I am thinking that class_eval affects
the greater class and "class_object" is used on a singleton class.
Are
they mutually exclusive?

class Dog
attr_accessor :age

def initialize(a)
@age = a
end
end

class << Dog
def greet
puts "hello"
end
end

Dog.class_eval{
def show
puts @age
end
}

Dog.greet #hello
d = Dog.new(5)
d.show #5
 
D

David A. Black

Hi --

What is the difference between class_eval and "class << object"?

It seems like they are the same. I am thinking that class_eval affects
the greater class and "class_object" is used on a singleton class. Are
they mutually exclusive?

class << object is the class keyword, which starts a class definition
block (in this case, on the singleton class of object) and therefore a
new local scope.

class_eval is a method, not a keyword, so it requires a receiver --
namely, a Module or Class object. It takes a block, and the block does
shares the variables of the existing local scope.


David

--
Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS April 14-17 New York City
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
See http://www.rubypal.com for details and updates!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top