0

Here's a code sample:

class Book
  def initialize
    @v = "abc"
  end
end

b = Book.new
b.instance_eval do
  def book_name
  end
end

Why do we use instance_eval to create a method (book_name) instead of adding book_name method inside class Book? The method (book_name) created using instance_eval will be accessible only by object b in the case above. Is there any particular use case?

sawa
  • 165,429
  • 45
  • 277
  • 381
rohan kharvi
  • 118
  • 10

2 Answers2

3

instance_eval is very useful when some kind of metaprogramming is needed, like when defining methods during instance initialization or inside frameworks.

Why use it? It's usually faster than calling define_method in these cases and, if adding a bunch of methods at the same time, invalidates the method cache just once.

On your specific example the method is being created only on the b instance, making it what is called a singleton method, meaning it only exists for this particular instance. The author could have used eval but since it evaluate code on a more global scope, it's considered unsafe.

Edit:

The same effect would be produced if you defined the method using b as the receiver

def b.book_name
end
Mereghost
  • 698
  • 4
  • 8
0

The author of this codes wanted book_name to be a method which belongs only to b. If he had created inside the class definition, it would belong to every object of class Book.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • Is that the only reason we use instance_eval – rohan kharvi Apr 03 '18 at 05:44
  • This is already mentioned in question. "The method(book_name) created using instance_eval will be accessible only by object b in above case" – Jagdeep Singh Apr 03 '18 at 05:49
  • @JagdeepSingh : I see that the question has been edited in the meantime. – user1934428 Apr 03 '18 at 09:58
  • @rohankharvi : No, there are several other uses for `instance_eval`, for example to access a instance variable of an object from the outside. Also, adding methods to an object can also be achieved in different ways. – user1934428 Apr 03 '18 at 10:01
  • @JagdeepSingh in this case, `define_singleton_method` would be a more idiomatic way to achieve the same result – Max Apr 03 '18 at 18:05
  • @Max: Since there is nothing dynamic about the method, neither the name nor the body, I would argue that the *only* idiomatic way would be `def`. – Jörg W Mittag Apr 04 '18 at 06:42