例如,我有一个包含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 :(得分: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 :(得分:2)
def some
send public_methods(false).sample
end
some
可以在此处致电some
:)
答案 2 :(得分:0)
def some
method_name = (self.public_methods - Object.instance_methods).sample
public_send(method_name)
end
这可能会为你做到:)