gpt4 book ai didi

ruby - 如何检查 ruby​​ 方法中可选参数的默认值是多少?

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:58 25 4
gpt4 key购买 nike

给定一个类,

class MyClass
def index(arg1, arg2="hello")
end
end

是否可以通过Class#instance_method 等方法获取arg2 的默认值?

最佳答案

似乎我们可以检查方法参数值的唯一方法是访问方法的 binding。使用 Tracepoint 类,我们可以获取这样一个绑定(bind)对象,然后检查所有 optional 参数的值。

我们需要确保只使用必需的参数调用所需的方法,以便为默认参数分配默认值。

下面是我尝试这样做的 - 它适用于实例方法和类方法。为了调用实例方法,我们需要实例化类 - 如果构造函数需要参数,那么创建对象可能会很棘手。为避免该问题,此代码动态创建给定类的子类并为其定义无参数构造函数。

class MyClass

# one arg constructor to make life complex
def initialize param
end

def index(arg1, arg2="hello", arg3 = 1, arg4 = {a:1}, arg5 = [1,2,3])
raise "Hi" # for testing purpose
end

def self.hi(arg6, arg7="default param")
end
end

def opt_values(clazz, meth)
captured_binding = nil

TracePoint.new(:call) do |tp|
captured_binding = tp.binding
end.enable {
# Dummy sub-class so that we can create instances with no-arg constructor
obj = Class.new(clazz) do
def initialize
end
end.new

# Check if it's a class method
meth_obj = clazz.method(meth) rescue nil

# If not, may be an instance method.
meth_obj = obj.method(meth) rescue nil if not meth_obj

if meth_obj
params = meth_obj.parameters
optional_params = params.collect {|i| i.last if i.first == :opt}.compact
dummy_required_params = [""] * (params.size - optional_params.size)

# Invoke the method, and handle any errors raise
meth_obj.call *dummy_required_params rescue nil

# Create a hash for storing optional argument name and its default value
optional_params.each_with_object({}) do |i, hash|
hash[i] = captured_binding.local_variable_get(i)
end
end
}
end

p opt_values MyClass, :index
#=> {:arg2=>"hello", :arg3=>1, :arg4=>{:a=>1}, :arg5=>[1, 2, 3]}
p opt_values MyClass, :hi
#=> {:arg7=>"default param"}

关于ruby - 如何检查 ruby​​ 方法中可选参数的默认值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com