Ruby 我不知道';我不知道如何从现有方法调用随机方法
例如,我有一个包含4个方法的类。在第四个方法中,我想调用一个随机方法 例如,此方法可以调用“first”、“second”或“third” 这可能会对您有所帮助:) 这可能会对您有所帮助:)Ruby 我不知道';我不知道如何从现有方法调用随机方法,ruby,random,methods,Ruby,Random,Methods,例如,我有一个包含4个方法的类。在第四个方法中,我想调用一个随机方法 例如,此方法可以调用“first”、“second”或“third” 这可能会对您有所帮助:) 这可能会对您有所帮助:) some可以调用some此处:) some可以打电话给some这里:)Ya但谁在乎呢;)即使它这样做了,它最终也会调用其中一个随机方法。另外,TIL:你可以将false发送到public\u方法和instance\u方法来获取对象自己的方法。@nzifnab我将false作为参数传递给public\u方法,
some
可以调用some
此处:)
some
可以打电话给some
这里:)Ya但谁在乎呢;)即使它这样做了,它最终也会调用其中一个随机方法。另外,TIL:你可以将false
发送到public\u方法和instance\u方法来获取对象自己的方法。@nzifnab我将false
作为参数传递给public\u方法
,不是吗?哇,我一直在使用nzifnab答案中的黑客public\u方法(false)
会更好。是的,但谁在乎呢;)即使它这样做了,它最终也会调用其中一个随机方法。另外,TIL:你可以将false
发送到public\u方法和instance\u方法来获取对象自己的方法。@nzifnab我将false
作为参数传递给public\u方法
,不是吗?哇,我一直在使用nzifnab答案中的黑客<代码>公共方法(false)
更好。很好地使用了\uuuuuuuuuuuuu方法。很好地使用了\uuuuuu方法。
class Test
def first
puts "1"
end
def second
puts "2"
end
def third
puts "3"
end
def some
end
end
test = Test.new
test.some
def some
method_name = (self.public_methods - Object.instance_methods).sample
public_send(method_name)
end
class Test
def first
puts "1"
end
def second
puts "2"
end
def third
puts "3"
end
def some
public_send (self.class.instance_methods(false) - [__method__]).sample
end
end
test = Test.new
test.some
# >> 1
def some
send public_methods(false).sample
end