Michael Gaskill Michael Gaskill - 6 months ago 9
Ruby Question

Ruby - calling methods named by symbol variables

I have a list of symbol names of methods that I'd like to call with some arguments. This is for a simple comparative testing facility that I'm trying to build. Here's the essential code for the testing:

data = [
["value", true],
["Value", true],
["VALUE", false],
["Not", false],
]

def test_value_1(string)
string == "value"
end

def test_value_2(string)
string.gsub(/.*?value.*?/, "\\1")
end

def test_value_3(string)
string.downcase == "value"
end

def test_value_4(string)
string.upcase == "value"
end

def test_value_5(string)
string.include?("value")
end

#tests
[:test_value_1, :test_value_2, :test_value_3, :test_value_4, :test_value_5].each do |method|
data.each do |test|
value = test[0]
expected_result = test[1]
puts "#{method}: #{method.to_proc.call(value) == expected_result ? 'Pass' : 'Fail'}: '#{value}'"
end
end


The important bit is the end block, following the
#tests
comment. The
data
and
test_value_*
methods are simply examples of how to use the testing block and have no inherent meaning themselves, so there's no need to dig into them.

This is the error output that I get:

>$ ruby symbol_methods.rb
symbol_methods.rb:33:in `call': private method `test_value_1' called for "value":String (NoMethodError)
from symbol_methods.rb:33:in `block (2 levels) in <main>'
from symbol_methods.rb:30:in `each'
from symbol_methods.rb:30:in `block in <main>'
from symbol_methods.rb:29:in `each'
from symbol_methods.rb:29:in `<main>'


I'm stumped. What would be the right way to call array of methods named as symbols in this case? I'm looking for both an explanation and a syntactically correct answer.

Answer

use send instead.

puts "#{method}: #{send(method, value) == expected_result ? 'Pass' : 'Fail'}: '#{value}'"