# Question about instance\_eval, dynamic methods and blocks

**URL:** <https://www.ruby-forum.com/t/question-about-instance-eval-dynamic-methods-and-blocks/114547>\
**Category:** Ruby\
**Created:** [September 14, 2007, 6:45pm UTC](https://www.ruby-forum.com/t/question-about-instance-eval-dynamic-methods-and-blocks/114547 "2007-09-14T18:45:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [September 14, 2007, 6:45pm UTC](https://www.ruby-forum.com/t/question-about-instance-eval-dynamic-methods-and-blocks/114547/1 "2007-09-14T18:45:14Z")

</div>

Not sure if I am attacking this correctly or not, so if anyone has any  
insight, please assist.

Let me setup my situation

class Task

attr\_reader :name

def initialize(name, &block)  
@name = name

```
instance_eval <<-EOL
  def run(&block)
    yield if block_given?
    # i need the block passed to initialize to go here
    # but i am not sure how do do it
  end
end

```

end  
end

t = Task.new(‘do\_something’) { puts “I want this block to be the guts of  
‘run’ method in t instance” }

t.run { “running #{@name}” }

basically i want to dynamically create the run method whenever i create  
an instance of a task, and the guts of the run method to be the block  
passed with .new but i also want the ability to have run accept a block  
as well.

any help is appreciated.

---

<div class="post-metadata">

**Author:** ![bigdaddy71](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bbe5ce/32.png) [@bigdaddy71](https://www.ruby-forum.com/u/bigdaddy71)\
**Post date:** [September 17, 2007, 1:25pm UTC](https://www.ruby-forum.com/t/question-about-instance-eval-dynamic-methods-and-blocks/114547/2 "2007-09-17T13:25:24Z")

</div>

Alle venerdÃ¬ 14 settembre 2007, Chris H. ha scritto:

> ```
> @name = name
> 
> ```
> 
> any help is appreciated.

I’m not sure whether I understand your question correctly. Can’t you  
store the  
block passed to initialize in an instance variable and call it from run?

class Task

attr\_reader :name

def initialize(name, &block)  
@name = name  
@block = block  
end

def run  
yield if block\_given?  
@block.call  
end

end

If you need to create the run method dynamically for other reasons, I  
think  
the simplest way to achieve what you want is still to store the block  
passed  
to initialize in an instance variable:

class Task

attr\_reader :name

def initialize name, &block  
@name = name  
@block = block  
instance\_eval do  
def self.run  
yield if block\_given?  
@block.call  
end  
end  
end

end

I hope this helps

Stefano
