我是 Ruby 新手,希望在方法内部使用方法或将construct_const 方法与解释方法相关联。解释方法应该简单地返回这个常量的值
def construct_const(value)
def interpret()
return @value
end
end
e = construct_const(0)
assert_equal(0, e.interpret)
我是 Ruby 新手,希望在方法内部使用方法或将construct_const 方法与解释方法相关联。解释方法应该简单地返回这个常量的值
def construct_const(value)
def interpret()
return @value
end
end
e = construct_const(0)
assert_equal(0, e.interpret)
在您的帖子中,您正在使用valueand @value。我想这是一个错字,因为您没有value在示例代码中引用任何地方,所以我假设您想value在您的interpret方法中使用,而不是@value.
您可以使用 为某个对象动态定义一个方法define_singleton_method,即
def construct_const(value)
define_singleton_method(:interpret) { value }
end
有了这个,如果你这样做,那么
e.construct_const
然后该变量e将附加一个新方法“解释”。
您可能已经有了更好的答案,但据我所知,这些似乎有效(尽管我真的不知道自己在做什么):
def construct_const(value)
mod = Module.new
mod.module_eval do
define_method :interpret do
value
end
end
obj = Object.new
obj.extend(mod)
obj
end
e = construct_const(0)
=> #<Object:0x00000000084a0e90>
e.interpret
=> 0
def construct_const(value)
obj = Object.new
obj.instance_eval do
@value = value
def interpret
@value
end
end
obj
end
e = construct_const(0)
=> #<Object:0x000000000a369098 @value=0>
e.interpret
=> 0
当你interpret在里面定义方法时,construct_const你会得到一个:interpret符号作为调用的结果construct_const。因为每条语句都返回一个值,定义一个方法返回方法名。
> def interpret()
> return @value
> end
=> :interpret
所以每次你调用construct_const你定义一个方法并返回它的名字。
此外,您不匹配局部变量value和实例变量@value。
您可以使用lambda 或 proc返回一个函数,该函数将具有call方法:
def construct_const(value)
-> { value }
end
> e = construct_const(0)
=> #<Proc:0x000055c060a47f60@(irb):12 (lambda)>
> e.call
=> 0
您可以使用方法定义匿名类interpret:
def construct_const(value)
my_class = Class.new do
def initialize(value)
@value = value
end
def interpret
@value # Here you can use an instance variable because it's inside of the anonymous class
end
end
my_class.new(value) # Pass a value to initialize a new instance
end
> e = construct_const(0)
=> #<#<Class:0x0000563663366c68>:0x0000563663366b50 @value=0>
> e.interpret
=> 0
类似的解决方案,但具有预定义的类:
class Interpreter
def initialize(value)
@value = value
end
def interpret
@value
end
end
def construct_const(value)
Interpreter.new(value)
end
> e = construct_const(0)
=> #<Interpreter:0x0000563663367b68 @value=0>
> e.interpret
=> 0
有Struct对象的解决方案:
def construct_const(value)
Struct.new(:interpret).new(value)
end
> e = construct_const(0)
=> #<struct interpret=0>
> e.interpret
=> 0