class_eval

D

Derek Chesterfield

Stealing someone else's recent example code, what is the difference
between this:
class A
def meth2
puts "I'm meth2. I try to access something I ain't
allowed: #{static_var}"
end
static_var = 3
define_method:)meth3) do
puts "I'm meth3. I'm allowed to access #{static_var}"
end
end
a = A.new
a.meth3
a.meth2

and this, which seems to do the same thing, but without the class_eval:
class B
def meth2
puts "I'm meth2. I try to access something I ain't
allowed: #{static_var}"
end
class_eval do
static_var = 3
define_method:)meth3) do
puts "I'm meth3. I'm allowed to access #{static_var}"
end
end
end
b = B.new
b.meth3
b.meth2

In other words, what does class_eval do that I'm not understanding?!
 
R

Robert Klemme

Derek said:
Stealing someone else's recent example code, what is the difference
between this:


and this, which seems to do the same thing, but without the
class_eval:


In other words, what does class_eval do that I'm not understanding?!

In this case it's not really interesting to use class_eval. It's more
interesting for cases like these
10
=> nil

And note the difference to instance_eval:
=> "ban">> Foo.instance_eval "def borg() 'org' end"
=> nilNoMethodError: undefined method `borg' for #<Foo:0x101b4e50>
from (irb):23
from :0=> "org"

HTH

Kind regards

robert
 

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,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top