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


264

当我运行一个简单的Ruby脚本时,将对象的字段转储到控制台的最简单方法是什么?

我正在寻找类似于PHP的东西print_r(),也可以与数组一起使用。

Answers:


420

可能:

puts variable.inspect

15
inspect您的类添加方法可以使您定义如何显示类的属性,而不是依赖默认输出。许多类都无法很好地实现它,但是在调试时它确实很有用。to_s如果无法找到inspect`方法,Ruby就会退一步。
Tin Man 2010年


5
server = TCPServer.new 0 ; puts server.inspect #<TCPServer:fd 9> => nil 。它不适用于大多数复杂的对象。
ribamar '16

至于找一个PHP时,这是第一个发现答案var_dump相当于在Ruby中,我发现pp很多usaful在这种情况下,看看这里- stackoverflow.com/questions/6501506/ruby-inspect-readability/...
拉宾

请注意,p object是一个别名puts object.inspect
扬Klimo

54

您可能会发现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"]

9
使用自省是Ruby的乐趣之一。instance_methods从有问题的类中减去一个对象,以获得唯一的方法通常很有用:(String.instance_methods - Object.instance_methods).sort
Tin Man 2010年

2
这应该是正确的答案,正如我在查找此页面时所期望的那样。
jaycode 2011年

.methods.sort非常有用 有什么“智能”方法可以快速显示(特定地)特定对象唯一的方法?例如,像这样的方法.to_s可能经常出现,因此它并不是那么有用,但是对于某些对象而言,了解某些方法可能非常方便。特别是在不太明显的情况下。有什么办法可以快速获得这些吗?(举例来说,我有一个PG::Result对象,并且想快速评估我可能发现有用的可能方法
。– stevec

50

to_yaml方法有时似乎很有用:

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

puts $foo.to_yaml

退货

--- 
:age: 43
:name: Clem

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


3
是的,to_yaml需要加载YAML模型。不过,它是Ruby标准库的一部分。
Chuck

当我尝试在Rails应用程序控制台中检查Amazon S3对象时,这很有用。
保罗


15

如果仅在对象中查找实例变量,则这可能会很有用:

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

或作为单行复制和粘贴:

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

10

把foo.to_json

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


4
to_json默认情况下未在1.8.7或1.9.2中加载。
Tin Man 2010年

5

如果要打印已经缩进的JSON

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

5

我遇到了这个线程,因为我正在寻找类似的东西。我喜欢这些答复,他们给了我一些想法,因此我测试了.to_hash方法,并且在用例上也非常有效。:

object.to_hash


1
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", "tom@tom.com", 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] 

4
undefined method 'attributes' for ...
yegor256 '16

3
object.attributes_name没用,但是object.attributes确实得到了很好的键和值哈希。这帮助了我,谢谢!
d3vkit's
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.