さて、これは私を夢中にさせています。このコードのポイントは、オブジェクトがobject.plusnumの形式である場合に、メソッドを動的に追加できるようにする必要があるということです。ここで、numは任意の数値です。これを機能させる方法がよくわかりません。これはこれまでの私のベストショットですが、現在いくつかのエラーが発生しています。
コード:
class Adder
def initialize(_val)
@start_value = _val
end
def method_missing(method_name, *args)
method = method_name.to_s
if method.start_with?("plus") then
num = method[4 .. method.length]
if (/^[\d]+(\.[\d]+){0,1}$/ === num) then
number = Integer(num)
self.class_eval("def #{method} return @start_value + #{number} end")
else
super
end
else
super
end
end
end
私が現在得ているエラーは、「class_eval」が未定義であるということです。私はメタプログラミングとルビーにかなり慣れていません、そしてこれは私を夢中にさせています。