mhaseeb mhaseeb - 5 months ago 6
Ruby Question

Using instance_eval to execute a block

I have the following class

MyClass
.

class MyClass
def initialize(&block)
if block_given?
self.instance_eval &block
p "Hey #{@name}, I have a message for you: #{@message}"
else
#do_something else
end
end

def say(message)
@message = message
#puts "how are you"
end

def to(name)
puts self.inspect
@name = name
end

end


I call this class with
MyClass.new { say('Hello').to('Haseeb') }
. But it throws me this error.

undefined method `to' for "Hello":String (NoMethodError).


The output should be
Hey Haseeb I have a message for you: Hello

Answer

You want to chain methods ⇒ return a receiver (self):

def say(message)
  @message = message
  self
end

In current implementation, say method returns a string and you are calling to method on returned value (a String instance,) resulting in error.

Comments