Ruby - Map methods of a class to others

def map_math_methods
    methods = Math.public_methods - Object.public_methods
    methods.each { |m|
        define_singleton_method(m, &Math.public_method(m))
    }
end

def main
    map_math_methods
    puts sin(1)
end

main
  • 输出
0.84147098
  • 提示
1. 可以通过 define_singleton_method 定义了一系列静态方法到当前的类。
2. Ruby 的数组是可以相减的,因为那些继承自 Object 的方法并不需要。

Math.public_methods - Object.public_methods
=> [:sqrt, :atan2, :cos, :sin, :tan, :acos, :asin, :atan, :cosh, :sinh, :tanh, :acosh, :asinh, :atanh, :exp, :log, :log2, :log10, :cbrt, :frexp, :ldexp, :hypot, :erf, :erfc, :gamma, :lgamma]