0

So basically, sometimes when I use JSON.parse and set the returned value to a variable, later in my app that variable will turn out to be NilClass.

What?

Take a look at this: Doing

require 'rest-client'

class Foo
  attr_reader :response
  @response = JSON.parse RestClient.get "http://path/to/api/?params"
end

foo = Foo.new
puts foo.response.class

prints out NilClass. Funky, right? On top of that, this means that all of the data within @response is rendered useless, as its inaccessible being of NilClass. Yet, just printing out foo.response will actually give all of data. Why is that? I made a workaround where within my method I set the Hash to a local variable and return that instead of a instance variable, but that's rather inconvenient.

1
  • You're not setting @response on any instance of Foo, but on the class Foo itself. What is your goal? Commented Jan 30, 2016 at 4:06

1 Answer 1

2

From the code given above, the @response is not a instance variable, it's a class instance variable.

foo.instance_variables   # => []
Foo.instance_variables   # => [:@response]

You can change the code like this

class Foo
  attr_reader :response

  def initialize
    @response = JSON.parse RestClient.get "http://path/to/api/?params"
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, so what if I change the class to instead be a module? Will the same problem still persist?
@dude0faw3 What's your actual purpose? Why do you want it to be a module? How will you be trying to use this functionality?
@dude0faw3 If you change the class to a module, then you cannot initiate a instance, but you can use the module methods or mixin the module to some other class. Depending on how you want to use it in your code.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.