How to get the code block to be executed from a file?

Hi,

When working with method blocks in ruby, how to get the code block to
be executed from a file? In the below example, I want to read the 2
lines in the block (line1, line2) from a file instead of directly
placing them as mentioned below. The following works fine, but when
passing these to lines (line1, line2) by reading from a file, ".call"
doesn't seem to be successful; no output; It doesn't throw any
exceptions
either.

def method_execution(&method_block)
    begin
      method_block.call
    rescue => msg
        fail("Test Failed : " + msg)
    end
end

def test
  method_execution{
    s = 5 + 4 # line 1
    puts s # line 2
  }
end

Any suggestions are appreciated. Thank you..

···

--
Posted via http://www.ruby-forum.com/.

You could have file with the method definitions in a class or Module
and require that file:

#file1.rb
require 'procdefs'

def method_execution(&method_block)
    begin
      method_block.call
    rescue => msg
        fail("Test Failed : " + msg)
    end
end

def test
  method_execution(&ProcDefs.get_proc("sum"))
end

#procdefs.rb
module ProcDefs
  def self.get_proc key
    {"sum" => proc{s = 5 + 4; puts s}, "product" => proc{s = 5*4; puts s}}[key]
  end
end

1.9.2p290 :021 > test
9

Jesus.

···

On Tue, Jul 10, 2012 at 4:30 PM, ni ed <lists@ruby-forum.com> wrote:

Hi,

When working with method blocks in ruby, how to get the code block to
be executed from a file? In the below example, I want to read the 2
lines in the block (line1, line2) from a file instead of directly
placing them as mentioned below. The following works fine, but when
passing these to lines (line1, line2) by reading from a file, ".call"
doesn't seem to be successful; no output; It doesn't throw any
exceptions
either.

def method_execution(&method_block)
    begin
      method_block.call
    rescue => msg
        fail("Test Failed : " + msg)
    end
end

def test
  method_execution{
    s = 5 + 4 # line 1
    puts s # line 2
  }
end

Any suggestions are appreciated. Thank you..

Thanks a lot.

···

--
Posted via http://www.ruby-forum.com/.