0

I'm using the Instagram API to get a user's feed of photos. The output looks something like this:

 [#<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>

I can happily loop through and display all the images or a specific one using this:

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

How is it possible to get a random result out and limit to only one image displayed? I've tried using limit(x) but that throws an error. Am just wanting to display one image at random, not the whole stream.

1
  • WOOOPW! Thanks, didn't even know about that. Cheers. S Jul 31, 2012 at 14:16

1 Answer 1

1
media = Instagram.user_recent_media(@client.user.id)
puts media.class

gives:

Array

knowing it's an array you can then easily get a random element using the sample method:

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

notice that the sample method is named choice in Ruby 1.8.7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.