I’m trying to write a Ruby program that will retrieve all the reddit usernames from a Json file. I can get it do display the list, but there is an error after the first username every time.
require 'net/http'
require 'rubygems'
require 'json'
require 'pp'
@response = Net::HTTP.get(URI.parse("http://www.reddit.com/r/AskReddit/comments/sl1nn /could_codeine_help_me_sleep_is_it_dangerous/.json"))
result = JSON.parse(@response)
comments = result[1]['data']['children'] #this is now an array of comment hashes
(0..comments.length).each do |i|
comment = comments[i]['data']
puts comment['author']
end
Although it displays the list, I also get this error:
in block in <main>': undefined method[]’ for nil:NilClass (NoMethodError)
Does anyone know I can solve this?
My guess is it’s the off by one error.
This is because
To be non-inclusive, you should use
..., that is:Better yet, since comments is an array, you can do: