2014-10-28 50 views
0

例如,我有一个有4种方法的类。在第四种方法中,我想调用一个随机方法。我不知道如何从现有方法调用随机方法

例如,这种方法可以称之为 “第一”, “第二” 或 “第三”

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 

回答

0
def some 
    method_name = (self.public_methods - Object.instance_methods).sample 
    public_send(method_name) 
end 

这可能会为你做它:)

2
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 
+1

很好的使用'__m ethod__'。 – 2014-10-28 17:39:59

2
def some 
    send public_methods(false).sample 
end 

some这里可以调用some :)

+0

雅,但谁在乎;)即使它它会最终调用随机方法之一。 – nzifnab 2014-10-28 16:57:04

+1

另外,TIL:你可以发送'false'到'public_methods'和'instance_methods'来获得对象的* own *方法。 – nzifnab 2014-10-28 16:57:57

+0

@nzifnab我将'false'作为参数传递给'public_methods',不是吗? – fl00r 2014-10-28 17:00:40

相关问题