Harry_Potter
Harry_Potter

Reputation: 49

Pass a method name as string to other method of different class in Ruby?

I have val1.rb and val2.rb, which have methods called foo1 and foo2 respectively, one start-up script called startup.rb and one main script called core.rb.

The startup script creates objects main_obj of the class from core.rb and objects obj1 and obj2 of classes of val1 and val2 respectively.

Core wishes to call a method which it accepts as an argument.

Below is the code that I wrote but it throws an error saying undefined method 'foo1'.

# #### foo1.rb #### #
class Test1
 def foo1(par1)
  puts "par1 is :#{par1}"
 end
end

# #### core.rb #### #
class Core
 def main_test (validation_obj, validation_method)
   par1 = 'sample'
   validation_obj.send :validation_method, par1
   # other way #
   # validation_method.call(par1)
 end 
end

# #### startup.rb #### #
require_relative 'core'
require_relative 'foo1'
require_realtive 'foo2'

main_obj = Core.new
testobj_1 = Test1.new
testobj_2 = Test2.new

method_name = 'foo1' # ==> want to pass this method as string 
main_obj.main_test(testobj_1, method_name)
method_name = 'foo2'
main_obj.main_test(testobj_2, method_name)

Any help is highly appreciated.

Upvotes: 0

Views: 242

Answers (1)

Andre Fonseca
Andre Fonseca

Reputation: 466

I think you need to transform your string in a symbol

"foo".to_sym

And your code:

class Core
 def main_test (validation_obj, validation_method)
   par1 = 'sample'
   validation_obj.send validation_method.to_sym, par1
   # other way #
   # validation_method.call(par1)
 end 
end

I believe this will make work your code.

Upvotes: 1

Related Questions