views:

221

answers:

1

Having looked at this question:

http://stackoverflow.com/questions/354547/print-ruby-object-members

I have a related issue. I'm relatively new to Ruby, so this is hopefully blindingly obvious. I have what I believe to be a Ruby object, generated from the MIME::Types library. I'm looking to get a simple file type for a particular file. Here's what happens in irb:

>> require 'mime/types'
=> ["MIME"]
>> text = MIME::Types['text/plain; charset=us-ascii']
=> [#<MIME::Type:0x2483ee0 @simplified="text/plain", @obsolete=nil, @raw_media_type="text", @content_type="text/plain", @system=nil, @registered=true, @url=["RFC2046", "RFC3676"], @media_type="text", @encoding="quoted-printable", @sub_type="plain", @raw_sub_type="plain", @extensions=["txt", "asc", "c", "cc", "h", "hh", "cpp", "hpp", "dat", "hlp"]>, #<MIME::Type:0x2476024 @simplified="text/plain", @obsolete=nil, @raw_media_type="text", @content_type="text/plain", @system=/vms/, @registered=true, @url=nil, @media_type="text", @encoding="8bit", @sub_type="plain", @raw_sub_type="plain", @extensions=["doc"]>]
>> puts text.media_type
NoMethodError: undefined method `media_type' for #<Array:0x2483af8>
    from (irb):4

My understanding is that I should be able to access this object's properties using dot syntax -- in fact, the page I learned this from (http://mime-types.rubyforge.org/) states exactly that! So how come I get a "no method" error instead? I've tried all kinds of other syntaxes, but no luck.

Thanks in advance, Aaron.

+7  A: 

MIME::Types returns an array of MIME::Type objects. Those objects respond as you would expect.

>> puts text[0].media_type
text
=> nil

Ruby's class method is useful for diagnosing this type of issue.

>> puts text.class
array
=> nil

You can also use the methods method to get a complete list of methods the object responds to.

Gordon Wilson
Additionally the error itself said it was an array: "NoMethodError: undefined method `media_type' for #<Array:0x2483af8>"
Vinko Vrsalovic