当我运行一个简单的Ruby脚本时,将对象的字段转储到控制台的最简单方法是什么?
我正在寻找类似于PHP的东西print_r()
,它也适用于数组.
可能是:
puts variable.inspect
您可能会发现该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"]
该to_yaml
方法有时似乎很有用:
$foo = {:name => "Clem", :age => 43} puts $foo.to_yaml
回报
--- :age: 43 :name: Clem
(这取决于YAML
正在加载的某个模块吗?或者这通常是否可用?)
p object
Ruby doc for p
.
p(*args) public
对于每个对象,直接将obj.inspect后跟换行符写入程序的标准输出.
如果您只是在对象中查找实例变量,这可能很有用:
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(":")}
把foo.to_json
可能会派上用场,因为默认情况下加载了json模块
如果要打印已缩进的JSON:
require 'json' ... puts JSON.pretty_generate(JSON.parse(object.to_json))