這個問題和我遇到的類似問題一直存在,我想了解從對象獲取值的思想過程,所以我可以解決類似的問題。通常從Ruby對象獲取值?
如果你有一個類似的例子,說明了相同的,那麼這只是一個好東西。
問題
如何獲得的Content-Length
價值?
你是如何得到解決方案的?
如果我做pp res
然後我得到
#<HTTP::Message:0x0055ab1ef42738
@http_body=
#<HTTP::Message::Body:0x0055ab1ef42698
@body=
"...",
@chunk_size=nil,
@positions=nil,
@size=0>,
@http_header=
#<HTTP::Message::Headers:0x0055ab1ef42710
@body_charset=nil,
@body_date=nil,
@body_encoding=#<Encoding:ASCII-8BIT>,
@body_size=0,
@body_type=nil,
@chunked=false,
@dumped=false,
@header_item=
[["Connection", "close"],
["Content-Type", "text/html"],
["Content-Length", "291"]],
@http_version="1.1",
如果我做pp res.methods
然後我看到http_header
,所以我temped認爲我可以通過pp res.http_header.header_item
接近Content-Length
,但這種失敗。
的pp res.http_header.methods
輸出是
[:[],
:[]=,
:dump,
:delete,
:add,
:all,
:get,
:set,
:request_query,
:content_type,
:body_encoding,
:http_version,
:http_version=,
:set_headers,
:request_uri,
:request_absolute_uri,
:request_absolute_uri=,
:set_date_header,
:request_method,
:body_size,
:chunked,
:status_code,
:reason_phrase,
:body_type,
:body_charset,
:body_date,
:init_connect_request,
:init_request,
:init_response,
:status_code=,
:content_type=,
:contenttype,
:contenttype=,
:set_body_encoding,
:body_size=,
:create_query_uri,
:create_query_part,
:chunked=,
:reason_phrase=,
:request_uri=,
:request_query=,
:body_type=,
:body_charset=,
:body_date=,
:methods,
:singleton_methods,
:protected_methods,
:private_methods,
:public_methods,
:to_yaml,
:to_yaml_properties,
:psych_to_yaml,
:pretty_print,
:pretty_print_cycle,
:pretty_print_instance_variables,
:pretty_print_inspect,
:instance_of?,
:public_send,
:instance_variable_get,
:instance_variable_set,
:instance_variable_defined?,
:remove_instance_variable,
:kind_of?,
:instance_variables,
:tap,
:public_method,
:singleton_method,
:is_a?,
:extend,
:define_singleton_method,
:method,
:awesome_print,
:to_enum,
:enum_for,
:awesome_inspect,
:ai,
:pretty_inspect,
:<=>,
:===,
:=~,
:!~,
:eql?,
:respond_to?,
:freeze,
:inspect,
:display,
:object_id,
:send,
:to_s,
:nil?,
:hash,
:class,
:singleton_class,
:clone,
:dup,
:itself,
:taint,
:tainted?,
:untaint,
:untrust,
:trust,
:untrusted?,
:frozen?,
:!,
:==,
:!=,
:__send__,
:equal?,
:instance_eval,
:instance_exec,
:__id__]
通過對象的內部挖掘一般是不是一個好主意。相反,你應該檢查對象的文檔,並儘可能使用它的公共接口。通常,課程不保證任何有關其內部表示的內容。任何更新都可以通過任何方式改變它,而外部接口通過暴露的方法通常會保持穩定。 –