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

我正在寻找与PHP的print_r()类似的东西,它也将与数组一起工作。


当前回答

把foo.to_json

可能会派上用场,因为json模块是默认加载的

其他回答

我偶然发现了这条线索,因为我正在寻找类似的东西。我喜欢他们的回答,他们给了我一些想法,所以我测试了.to_hash方法,并在用例中工作得很好。秀:

object.to_hash

如果你想打印一个已经缩进的JSON:

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

可能是:

puts variable.inspect

您可能会发现method方法的用法,它为对象返回一个方法数组。它与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"]

to_yaml方法有时似乎很有用:

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

puts $foo.to_yaml

返回

--- 
:age: 43
:name: Clem

(这是否依赖于某些YAML模块被加载?或者这通常是可行的?)