2010-09-08 33 views
1

我正在使用ruby-aaws gem访问Amazon AWS API,但没有深入了解API或创业板的细节,我认为我的问题更多的是一般性质。在Rails中访问具有保留关键字作为名称的对象值

当我查询API时,我将以“object array”结尾,我们将其称为item,其中包含API响应。 我可以轻松访问数组中的数据,例如puts item.item_attributes.artist.to_s

现在API返回标识符是Rails中保留字的属性,例如, 格式绑定

所以这样做:
puts item.item_attributes.format.to_s将返回未找到

方法而
puts item.item_attributes.binding.to_s会返回一些对象哈希像#<Binding:0xb70478e4>

我可以看到有那个名字值从产生YAML做
puts item.item_attributes.to_yaml

片段时显示艺术家结合
--- !seq:Amazon::AWS::AWSArray
- !ruby/object:Amazon::AWS::AWSObject::ItemAttributes
__val__:
artist: !seq:Amazon::AWS::AWSArray
- !ruby/object:Amazon::AWS::AWSObject::Artist
__val__: Summerbirds in the Cellar
binding: !seq:Amazon::AWS::AWSArray
- !ruby/object:Amazon::AWS::AWSObject::Binding
__val__: Vinyl

这可能是一个非常详细解释一个非常简单的解决方案,但我似乎无法找到解决方案。

编辑
终于找到了。我想这是因为它是对象的数组,咄... puts item.item_attributes[0].binding.to_s

+0

'item.binding'返回什么? – Eric 2010-09-08 07:50:19

+0

'Object#binding'返回该对象的范围。这是红宝石,而不是铁轨。 – Reactormonk 2010-09-08 08:32:15

+0

item.binding返回nil。问题是我不能使用item.item_attributes.binding作为语法,因为'binding'是一个保留字。虽然像“艺术家”这样的词不是,因此item.item_attributes.artist起作用。 – capsized 2010-09-08 11:19:23

回答

0

终于找到了。我猜这是因为它是一个对象数组,所以...
puts item.item_attributes[0].binding.to_s

0

您可以通过使用[]代替方法名(这是使用method_missing反正大概提供)来访问单个属性。

因此,item.item_attributes[:artist].to_s可能会返回你想要的。如果它不是,那么值得尝试'artist'作为关键。

+0

不工作的错误信息是:'[]':符号作为数组索引(TypeError) – capsized 2010-09-08 11:13:44

+0

啊,看起来像项目['艺术家']可能会做你想做的。让我知道,我会更新我的答案。 – Shadwell 2010-09-08 11:40:43

+0

无效:'[]':不能将String转换为Integer(TypeError) – capsized 2010-09-08 12:03:35

相关问题