Posts

Showing posts from February, 2018

Ruby's class_eval & instance_eval. Is it that confusing?

Image
We can do class_eval & instance_eval using following syntax,
In this example, class_eval? method can be accessed my any objects of the String class. Where as instance_eval? method can be accessed by only String class. 

More clearly, class_eval creates instance methods, but instance_eval creates class methods or it can be applied to only one object at a time.

[3] pry(main)> String.class_eval?
NoMethodError: undefined method `class_eval?' for String:Class
Did you mean?  class_eval
from (pry):3:in `<main>'
[4] pry(main)> String.instance_eval?
=> true
[5] pry(main)> String.new.class_eval?
=> true

my_string = "This is a string"

For example you can simply do like below as any string is an object of String Class
[5] pry(main)> my_string.class_eval?
=> true

But you can not do 
[7] pry(main)> my_string.instance_eval?
NoMethodError: undefined method `instance_eval?' for "This is a string":String