Rilcon42
Rilcon42

Reputation: 9763

how to add single element to array object

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

Upvotes: 2

Views: 60

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

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.

Upvotes: 1

JVon
JVon

Reputation: 694

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).

Upvotes: 3

Related Questions