Ruby-如何将方法与另一个方法关联
我是Ruby新手,希望在方法内部使用方法,或者将construct_const方法与exploration方法相关联。explorate方法应该只返回该常量的值Ruby-如何将方法与另一个方法关联,ruby,expression,Ruby,Expression,我是Ruby新手,希望在方法内部使用方法,或者将construct_const方法与exploration方法相关联。explorate方法应该只返回该常量的值 def construct_const(value) def interpret() return @value end end 在您的帖子中,您使用的是value和@value。我猜这是一个输入错误,因为您没有在示例代码中的任何地方引用value,所以我假设您希望在解释方法中使用value,而不是@value
def construct_const(value)
def interpret()
return @value
end
end
在您的帖子中,您使用的是
value
和@value
。我猜这是一个输入错误,因为您没有在示例代码中的任何地方引用value
,所以我假设您希望在解释方法中使用value
,而不是@value
您可以使用为特定对象动态定义方法,即
有了这个,如果你这样做了
e.construct_const
变量e
将附加一个新的方法“exploration”。当您在construct\u const
中定义exploration
方法时,您会得到一个:exploration
符号,作为调用construct\u const
的结果。因为每个语句都返回一个值,定义一个方法时会返回方法名
> def interpret()
> return @value
> end
=> :interpret
因此,每次调用construct\u const
时,都要定义一个方法并返回其名称
此外,局部变量值
与实例变量@value
不匹配
您可以使用返回函数,该函数将具有call
方法:
def construct_const(value)
-> { value }
end
> e = construct_const(0)
=> #<Proc:0x000055c060a47f60@(irb):12 (lambda)>
> e.call
=> 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
你可能已经有了更好的答案,但据我所知,这些答案似乎有效(尽管我真的不知道我在做什么):
def构造常数(值)
mod=模块。新
模块评估do模块
定义方法:解释do
价值
结束
结束
obj=Object.new
对象扩展(mod)
obj
结束
e=构造常数(0)
=> #
e、 诠释
=> 0
def构造常数(值)
obj=Object.new
obj.instance_eval do
@价值=价值
def解释
@价值观
结束
结束
obj
结束
e=构造常数(0)
=> #
e、 诠释
=> 0
def construct_const(value)
-> { value }
end
> e = construct_const(0)
=> #<Proc:0x000055c060a47f60@(irb):12 (lambda)>
> e.call
=> 0
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
def construct_const(value)
Struct.new(:interpret).new(value)
end
> e = construct_const(0)
=> #<struct interpret=0>
> e.interpret
=> 0
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