[英]Ruby Object Member Access: How's that Done?
Having looked at this question: 看了这个问题:
How do I dump an object's fields to the console? 如何将对象的字段转储到控制台?
I have a related issue. 我有一个相关的问题。 I'm relatively new to Ruby, so this is hopefully blindingly obvious. 我对Ruby比较陌生,所以希望这很明显。 I have what I believe to be a Ruby object, generated from the MIME::Types library. 我有我认为是从MIME :: Types库生成的Ruby对象。 I'm looking to get a simple file type for a particular file. 我希望得到一个特定文件的简单文件类型。 Here's what happens in irb: 这是在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! 我的理解是我应该能够使用点语法访问这个对象的属性 - 实际上,我从( http://mime-types.rubyforge.org/ )学到的这个页面就是这样说的! 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. 先谢谢,亚伦。
MIME::Types
returns an array of MIME::Type
objects. MIME::Types
返回MIME::Type
对象的数组。 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. Ruby的class
方法对于诊断此类问题很有用。
>> puts text.class
array
=> nil
You can also use the methods
method to get a complete list of methods the object responds to. 您还可以使用methods
方法获取对象响应的方法的完整列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.