Rails Hashie输出

时间:2012-07-25 03:39:29

标签: ruby-on-rails ruby ruby-on-rails-3

这是我的问题,我从请求中获取变量并将其存储在@response中。

然后我调试响应,调试(@response),并获得此输出:

--- !ruby/hash:Hashie::Mash
results:
- !ruby/hash:Hashie::Mash
  id: '33098557'
  firstName: john
  lastName: star
  relationship: self
  photo: https://foursquare.com/img/blank_boy.png
  tips: !ruby/hash:Hashie::Mash
    count: 0
  lists: !ruby/hash:Hashie::Mash
    groups:
    - !ruby/hash:Hashie::Mash
      type: created
      count: 1
      items: []
  gender: male
  homeCity: mexico
  bio: ''
  contact: !ruby/hash:Hashie::Mash
    email: jhon@hotmail.com
unmatched: !ruby/hash:Hashie::Mash
  email: []

我可以通过输入@ response.results来获得结果,然后对此进行调查:

---
- !ruby/hash:Hashie::Mash
  id: '33098557'
  firstName: john
  lastName: star
  relationship: self
  photo: https://foursquare.com/img/blank_boy.png
  tips: !ruby/hash:Hashie::Mash
    count: 0
  lists: !ruby/hash:Hashie::Mash
    groups:
    - !ruby/hash:Hashie::Mash
      type: created
      count: 1
      items: []
  gender: male
  homeCity: mexico
  bio: ''
  contact: !ruby/hash:Hashie::Mash
    email: jhon@hotmail.com

但我无法获得内部属性,如电子邮件或名字,我如何访问这些属性???

1 个答案:

答案 0 :(得分:3)

@responseHashie::Mash的实例,而@response.resultsArray的实例,因此您需要访问要接收结果的数组的索引对

@response.results[0].firstName
@response.results[0].contact.email

将分别返回第一个结果的firstNameemail的值。您可以遍历响应(如果碰巧有多个,则获取所有结果)

@response.results.each do |result|
  result.firstName
  result.contact.email
end

如果始终只有一个result,您也可以使用Ruby的.first方法

来访问它
@response.results.first.email
# ...