【问题标题】:Get Random Result and Limit Output from Hashie::Mash Loop Ruby on Rails从 Hashie::Mash Loop Ruby on Rails 获取随机结果和限制输出
【发布时间】:2012-07-31 11:04:49
【问题描述】:

我正在使用 Instagram API 来获取用户的照片提要。输出如下所示:

 [#<Hashie::Mash attribution=nil caption=nil comments=#<Hashie::Mash count=0 data=[]> created_time="1330231732" filter="Sutro" id="1403234234201396589_3002382" images=#<Hashie::Mash low_resolution=#<Hashie::Mash height=306 url="http://distilleryimage5.s3.amazonaws.com/8fd08dfsdfsdf111e180d51231380fcd7e_6.jpg" width=306>

我可以愉快地循环显示所有图像或使用这个:

  Instagram.user_recent_media(@client.user.id).each do |test|
    %img{:src=>"#{test.images.low_resolution.url}"}

如何获得随机结果并限制只显示一张图片?我试过使用 limit(x) 但这会引发错误。我只想随机显示一张图像,而不是整个流。

【问题讨论】:

  • 哇!谢谢,连这个都不知道。干杯。 S

标签: ruby json api instagram


【解决方案1】:
media = Instagram.user_recent_media(@client.user.id)
puts media.class

给予:

Array

知道它是一个数组,然后您可以使用sample 方法轻松获取随机元素:

random = media.sample
puts "#{random.images.low_resolution.url}"

注意 sample 方法在 Ruby 1.8.7 中被命名为 choice

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2013-09-09
    相关资源
    最近更新 更多