如何在Ruby中访问此值?

时间:2013-04-15 05:21:41

标签: ruby object yaml

对Ruby完全陌生,查看文档并且似乎无法找到我正在寻找的东西。我有一个对象,我正在尝试深入研究它以获取某些东西。对象推文[0]看起来像这样......

--- !ruby/object:Twitter::Tweet
attrs:
  :created_at: Wed Apr 10 00:58:21 +0000 2013
  :user:
    :location: ''
    :entities:
      :description:
        :urls: []
    :protected: false
  :geo:
  :entities:
    :hashtags:
    - :text: adult
      :indices:
      - 34
      - 40
    :urls: []
    :user_mentions: []
    :media:
      :indices:
      - 41
      - 63
      :url: http:t.co/i-need-this-image
      :type: photo
      :sizes:
        :thumb:
          :w: 150
          :h: 150
          :resize: crop
        :small:
          :w: 340
          :h: 453
          :resize: fit
        :medium:
          :w: 600
          :h: 800
          :resize: fit
        :large:
          :w: 768
          :h: 1024
          :resize: fit

我尝试了很多不同的方法,但似乎都没有正常工作。为了把它们丢弃,我一直在使用

puts YAML::dump(tweets[0])
--
puts YAML::dump(tweets[0].media) # returns the media method correctly
puts YAML::dump(tweets[0]['media']) # also seems to do it
puts YAML::dump(tweets[0].media.url) # idk
puts YAML::dump(tweets[0]['media']['url']) # I feel like this should work but it doesn't

1 个答案:

答案 0 :(得分:1)

以下对我有用:

require 'yaml'
tweets = YAML.load_file('test.yml') # this file contains a copy of the YAML
p tweets["attrs"][:entities][:media][:url] # "http:t.co/i-need-this-image"