간단한 Ruby 스크립트를 실행할 때 객체의 필드를 콘솔에 덤프하는 가장 쉬운 방법은 무엇입니까?
print_r()
배열과 함께 작동 하는 PHP와 비슷한 것을 찾고 있습니다.
답변
혹시:
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
로드중인 일부 모듈에 달려 있습니까? 아니면 일반적으로 사용 가능합니까?)
답변
답변
객체에서 인스턴스 변수 만 찾고 있다면 유용 할 수 있습니다.
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))
