2

How can I append a single value to an array that is stored as an object of the class Citations?

class Citations
    attr_accessor :paper,:arr

    def dothing()
        return paper.to_s.length
    end 
end

cit = Citations.new


#(1...5).each{ |x| cit.arr << x } # fails
cit.arr = [1,2,3,4] # works if I add the entire array as one unit
puts cit.arr

2 Answers 2

3

It fails because the array arr is not initialized. Change your class to this:

class Citations
    attr_accessor :paper,:arr
    def initialize
        @arr = []
    end
    def dothing()
        return paper.to_s.length
    end 
end

Naturally, your second attempt works fine because by using

cit.arr = [1,2,3,4]

You are in fact initializing it.

I can see a similar issue happening to paper (whatever it is).

Sign up to request clarification or add additional context in comments.

Comments

1

In your code, this line: (1...5).each { |x| cit.arr << x } fails with error message:

undefined method `<<' for nil:NilClass (NoMethodError)

If you read the error message carefully, you will see that it indicates: cit.arr is nil because you did not initialize it and so when you call this: cit.arr << x, it's actually trying to call << method on the nil and fails because << method is not implemented on NilClass objects.

So, you need to initialize arr before calling cit.arr << x so that cit.arr is not nil.

You can do that in the initialize method of your class like this:

class Citations
    attr_accessor :paper,:arr

    def initialize
        @arr = []
    end
# rest of the codes
end

This will fix your problem.

Comments

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.