gpt4 book ai didi

Ruby - 打印变量名,然后打印它的值

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

编写函数(或 DSLish 的东西)的最佳方法是什么,可以让我用 Ruby 编写此代码。我将如何构建函数 write_pair?

username = "tyndall"
write_pair username
# where write_pair username outputs
username: tyndall

可以吗?寻找最简单的方法来做到这一点。

最佳答案

当然可以!

我的解决方案通过 Object#object_id 身份测试 var:http://codepad.org/V7TXRxmL
它在绑定(bind)传递样式中被削弱了......
虽然它只适用于本地变量,但可以很容易地使其成为“通用”的,添加使用其他范围变量列表方法,如 instance_variables 等。

# the function must be defined in such a place 
# ... so as to "catch" the binding of the vars ... cheesy
# otherwise we're kinda stuck with the extra param on the caller
@_binding = binding
def write_pair(p, b = @_binding)
eval("
local_variables.each do |v|
if eval(v.to_s + \".object_id\") == " + p.object_id.to_s + "
puts v.to_s + ': ' + \"" + p.to_s + "\"
end
end
" , b)
end

# if the binding is an issue just do here:
# write_pair = lambda { |p| write_pair(p, binding) }

# just some test vars to make sure it works
username1 = "tyndall"
username = "tyndall"
username3 = "tyndall"

# the result:
write_pair(username)
# username: tyndall

关于Ruby - 打印变量名,然后打印它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2603617/

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