我有一個我想用一些參數調用的方法的符號名稱列表。這是我想要建立的一個簡單的比較測試工具。下面是測試的基本代碼:Ruby - 調用由符號變量命名的方法
data = [
["value", true],
["any value here", true],
["Value", true],
]
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
#tests
[:test_value_1, :test_value_2, :test_value_3].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
最重要的一點是終端模塊,繼#tests
評論。 data
和test_value_*
方法僅僅是如何使用測試塊的例子,它們本身沒有固有的意義,所以沒有必要深入研究它們。
我真正想要做下來歸結到這個代碼片段:
method.to_proc.call(value)
在這種情況下,value
是在全局命名空間的方法的符號名(不直接的方法目的)。
這是錯誤輸出,我得到:
>$ 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>'
我難倒。我試過public_send(method, value)
和method.to_proc.call(value)
,但都導致private method
錯誤。
在這種情況下,調用名爲符號的方法的正確方法是什麼?我正在尋找解釋和句法正確的答案。
@mudasobwa這裏的要點是調用一個私有方法。 'public_send'正是不起作用的。 – sawa
@sawa哦,確實,對此感到抱歉。 – mudasobwa
@delta這相當於'send(method,value == expected_result?'Pass':'Fail')' - 它應該是'send(method,value)== expected_result? '通過':'失敗'。 Parens很重要。 –