programing

개체의 필드를 콘솔에 덤프하려면 어떻게 해야 합니까?

lovejava 2023. 7. 13. 20:13

개체의 필드를 콘솔에 덤프하려면 어떻게 해야 합니까?

간단한 루비 스크립트를 실행할 때 개체의 필드를 콘솔에 덤프하는 가장 쉬운 방법은 무엇입니까?

저는 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

다음을 위한 루비 문서p.

p(*args) public

각 개체에 대해 obj.inspect를 직접 쓴 다음 프로그램의 표준 출력에 새 줄을 씁니다.

개체에서 인스턴스 변수만 찾는 경우 유용할 수 있습니다.

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(":")}

puts foo.to _json

json 모듈은 기본적으로 로드되므로 유용할 수 있습니다.

이미 들여쓴 JSON을 인쇄하려는 경우:

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

저는 비슷한 것을 찾고 있었기 때문에 이 실을 발견했습니다.저는 반응이 마음에 들고 아이디어를 주셔서 .to_hash 방법을 테스트했고 사용 사례에서도 잘 작동했습니다.soo:

object.to_hash

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] 

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)>

자체 솔루션을 사용하여 변수를 인쇄하고 있습니다. https://github.com/igorkasyanchuk/wrapped_print .

간단히 전화할 수 있습니다.user.wp로그에서 이 변수의 값을 확인합니다.

다음 대신:

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

언급URL : https://stackoverflow.com/questions/354547/how-do-i-dump-an-objects-fields-to-the-console