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

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)>
=> 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


Popular posts from this blog

Rails Kaminari - Ajax pagination

Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value: '\xF0\x9F\x8C\x9D')