如何将对象的字段转储到控制台?
当我运行简单的 Ruby 脚本时,将对象的字段转储到控制台的最简单方法是什么?
我正在寻找类似于 PHP 的 print_r() 的东西,它也适用于数组。
When I'm running a simple Ruby script, what's the easiest way to dump an object's fields to the console?
I'm looking for something similar to PHP's print_r()
that will work with arrays as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
可能:
Possibly:
您可能会发现
methods
方法的用途,它返回对象的方法数组。 它与print_r
不同,但有时仍然有用。You might find a use for the
methods
method which returns an array of methods for an object. It's not the same asprint_r
, but still useful at times.to_yaml 方法有时似乎很有用:
返回
(这是否取决于正在加载的某些
YAML
模块?或者通常可用?)The
to_yaml
method seems to be useful sometimes:returns
(Does this depend on some
YAML
module being loaded? Or would that typically be available?)p
的 Ruby 文档。Ruby doc for
p
.如果您只想查找对象中的实例变量,这可能很有用:
或者作为复制和粘贴的单行代码:
If you're looking for just the instance variables in the object, this might be useful:
or as a one-liner for copy and pasting:
foo.to_json
可能会派上用场,因为默认情况下会加载 json 模块
puts foo.to_json
might come in handy since the json module is loaded by default
如果您想打印已经缩进的 JSON:
If you want to print an already indented JSON:
我遇到这个线程是因为我正在寻找类似的东西。 我喜欢这些回复,他们给了我一些想法,所以我测试了 .to_hash 方法,并且对于用例也非常有效。 soo:
object.to_hash
I came across this thread because I was looking for something similar. I like the responses and they gave me some ideas so I tested the .to_hash method and worked really well for the use case too. soo:
object.to_hash
pp File.stat('/tmp')
pp File.stat('/tmp')
我正在使用自己的解决方案来打印和调试变量 https://github.com/igorkasyanchuk/wrapped_print
您可以简单地调用
user.wp
在日志中查看此变量的值,而不是:
I'm using own solution to print and debug variables is https://github.com/igorkasyanchuk/wrapped_print
you can simply call
user.wp
to see in the logs a value of this variableinstead of: