Ruby - 输出变量名称和值 [英] Ruby - print the variable name and then its value

查看:302
本文介绍了Ruby - 输出变量名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个函数(或某种DSL文件)的最佳方法是让我可以在Ruby中编写这段代码。我将如何构造write_pair函数?

pre $ username =tyndall
write_pair username
#where write_pair用户名输出
用户名:tyndall

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

解决方案

确实有可能!

我的解决方案通过Object#object_id identity来测试var: http: //codepad.org/V7TXRxmL

它在绑定传递风格中变成了残缺......

虽然它仅适用于本地变量,但它可以很容易地制作通用增加了其他范围变量列表方法的使用,如 instance_variables 等。

 #这个函数必须在这样的地方定义
#...以便捕获变量的绑定... cheesy
#否则我们会被卡住调用者的额外参数
@_binding = binding
def write_pair(p,b = @_binding)
eval(
local_variables.each do | v |
如果eval(v.to_s + \.object_id \)==+ p.object_id.to_s +
puts v.to_s +':'+ \+ p.to_s + \
end
end
,b)
end

#如果绑定是一个问题,只需在这里执行:
# write_pair = lambda {| p | write_pair(p,binding)}

#只是一些测试变量,以确保它能正常工作
username1 =tyndall
username =tyndall
username3 = tyndall

#结果:
write_pair(username)
#username:tyndall


What is the best way to write a function (or something DSLish) that will allow me to write this code in Ruby. How would I construct the function write_pair?

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

Is it possible to do? Looking for the most simple way to do this.

解决方案

Sure it is possible!

My solution tests the var by Object#object_id identity: http://codepad.org/V7TXRxmL
It's crippled in the binding passing style ...
Although it works just for local vars yet, it can be easily be made "universal" adding use of the other scope-variable-listing methods like instance_variables etc.

# 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 - 输出变量名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆