Double less than Ruby access
I am still very new to Ruby and was wondering how I would access a data element stored in a "double less than" structure:
@email << {:envelope => envelope, :body => body}
If I do
<% @results.email.each do |result| %>
<%= result %>
<% end %>
I get
bodyTEST TEST envelope#<struct Net::IMAP::Envelope date="Tue, 28 Jun 2011 09:20:35 -0700", subject="TEST TEST", from=[#<struct Net::IMAP::Address name="Some Name", route=nil, mailbox="someinbox", host="somehost.com">], sender=[#<struct Net::IMAP::Address name="Somename", route=nil, mailbox="somebox", host="somedomaincom">开发者_C百科], reply_to=[#<struct Net::IMAP::Address name="SomePerson", route=nil, mailbox="somemailbox", host="somehost.com">], to=[#<struct Net::IMAP::Address name=nil, route=nil, mailbox="thisinbox", host="somehost.com">], cc=nil, bcc=nil, in_reply_to=nil, message_id="<C4427977-8A42-46E4-ADB4-1AE88ED9CCDE@mehost.com>">
How do access each element, like body, envelope, sender (within envelope)? result.body
doesn't work, nor does result[body]
.
Thanks!
You should use result[:body]
and not result[body]
. body
is a variable, whereas :body
is a symbol (similar to a string).
Notice that you have stored values in the hash with symbols. {:envelope => envelope; :body => body}
is storing the content of the variable envelope
(the one on the right) as the value against the key :envelope
(and the same for body
and :body
).
Note: This is a nice write up on how Symbols differ from Strings - http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/
@email << {:envelope => envelope, :body => body}
is simply adding the hash to the @email
variable. If it is an Array
, then you are adding an element, otherwise, it depends on the implementation of the #<<
method. To access the elements, use hash lookup syntax:
result[:envelope] #=> returns the envelope object
result[:envelope].sender #=> returns the envelopes sender
result[:body] #=> returns the body
精彩评论