2010-09-08 34 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

相關問題