如何将对象的字段转储到控制台?

发布于 2024-07-10 05:19:38 字数 94 浏览 7 评论 0原文

当我运行简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

娇纵 2024-07-17 05:19:38

可能:

puts variable.inspect

Possibly:

puts variable.inspect
趁年轻赶紧闹 2024-07-17 05:19:38

您可能会发现 methods 方法的用途,它返回对象的方法数组。 它与 print_r 不同,但有时仍然有用。

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]
吹梦到西洲 2024-07-17 05:19:38

to_yaml 方法有时似乎很有用:

$foo = {:name => "Clem", :age => 43}

puts $foo.to_yaml

返回

--- 
:age: 43
:name: Clem

(这是否取决于正在加载的某些 YAML 模块?或者通常可用?)

The to_yaml method seems to be useful sometimes:

$foo = {:name => "Clem", :age => 43}

puts $foo.to_yaml

returns

--- 
:age: 43
:name: Clem

(Does this depend on some YAML module being loaded? Or would that typically be available?)

起风了 2024-07-17 05:19:38
p object

p 的 Ruby 文档。

p(*args) 公共

对于每个对象,后面直接写obj.inspect
通过程序标准输出的换行符。

p object

Ruby doc for p.

p(*args) public

For each object, directly writes obj.inspect followed
by a newline to the program’s standard output.

oО清风挽发oО 2024-07-17 05:19:38

如果您只想查找对象中的实例变量,这可能很有用:

obj.instance_variables.each do |var|
  puts [var, obj.instance_variable_get(var).inspect].join(":")
end

或者作为复制和粘贴的单行代码:

obj.instance_variables.each{ |var| puts [var, obj.instance_variable_get(var).inspect].join(":")}

If you're looking for just the instance variables in the object, this might be useful:

obj.instance_variables.each do |var|
  puts [var, obj.instance_variable_get(var).inspect].join(":")
end

or as a one-liner for copy and pasting:

obj.instance_variables.each{ |var| puts [var, obj.instance_variable_get(var).inspect].join(":")}
你是年少的欢喜 2024-07-17 05:19:38

foo.to_json

可能会派上用场,因为默认情况下会加载 json 模块

puts foo.to_json

might come in handy since the json module is loaded by default

他夏了夏天 2024-07-17 05:19:38

如果您想打印已经缩进的 JSON

require 'json'
...
puts JSON.pretty_generate(JSON.parse(object.to_json))

If you want to print an already indented JSON:

require 'json'
...
puts JSON.pretty_generate(JSON.parse(object.to_json))
澉约 2024-07-17 05:19:38

我遇到这个线程是因为我正在寻找类似的东西。 我喜欢这些回复,他们给了我一些想法,所以我测试了 .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

简单爱 2024-07-17 05:19:38
object.attribute_names

# => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_token", "admin", "marketing_permissions", "terms_and_conditions", "disable", "black_list", "zero_cost", "password_reset_token", "password_reset_sent_at"]


object.attributes.values

# => [1, "tom", "[email protected]", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, "$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm", "2dd1829c9fb3af2a36a970acda0efe5c1d471199", true, nil, nil, nil, nil, nil, nil, nil] 
object.attribute_names

# => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_token", "admin", "marketing_permissions", "terms_and_conditions", "disable", "black_list", "zero_cost", "password_reset_token", "password_reset_sent_at"]


object.attributes.values

# => [1, "tom", "[email protected]", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, "$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm", "2dd1829c9fb3af2a36a970acda0efe5c1d471199", true, nil, nil, nil, nil, nil, nil, nil] 
方圜几里 2024-07-17 05:19:38

pp File.stat('/tmp')

#<File::Stat
 dev=0x1000004,
 ino=71426291,
 mode=041777 (directory rwxrwxrwt),
 nlink=15,
 uid=0 (root),
 gid=0 (wheel),
 rdev=0x0 (0, 0),
 size=480,
 blksize=4096,
 blocks=0,
 atime=2021-04-20 17:50:33.062419819 +0800 (1618912233),
 mtime=2021-04-21 11:35:32.808546288 +0800 (1618976132),
 ctime=2021-04-21 11:35:32.808546288 +0800 (1618976132)>

pp File.stat('/tmp')

#<File::Stat
 dev=0x1000004,
 ino=71426291,
 mode=041777 (directory rwxrwxrwt),
 nlink=15,
 uid=0 (root),
 gid=0 (wheel),
 rdev=0x0 (0, 0),
 size=480,
 blksize=4096,
 blocks=0,
 atime=2021-04-20 17:50:33.062419819 +0800 (1618912233),
 mtime=2021-04-21 11:35:32.808546288 +0800 (1618976132),
 ctime=2021-04-21 11:35:32.808546288 +0800 (1618976132)>
春风十里 2024-07-17 05:19:38

我正在使用自己的解决方案来打印和调试变量 https://github.com/igorkasyanchuk/wrapped_print

您可以简单地调用 user.wp 在日志中查看此变量的值,

而不是:

puts "-"*10
puts user.inspect
puts "-"*10

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 variable

instead of:

puts "-"*10
puts user.inspect
puts "-"*10
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文