Alejo Ribes
Alejo Ribes

Reputation: 1415

Create array object in a class, ruby

I have created two classes, Blog and Post, try to create an array of Post, in Blog, shows me the following error: "undefined method` push 'for {}: Hash "

How I can do to keep in the Array?

class Blog
    def initialize
        @post = {}
    end
    def addPost (newPost)
#Here I try to add an object blog, post an array of objects
        @post.push(newPost)
    end
end
class Post
    def initialize title, date, text
        @title = title
        @date = date
        @text = text
    end
    def printPost
        puts "#{@title} \n #{@date} \n ****************** \n #{@text}"
    end
end
myBlog = Blog.new
firstPost = Post.new("First Post", "21/12/2014", "This is my first post on my first blog")
secondPost = Post.new("Second Post", "11/10/2015", "This is my seocond post on my first blog")
myBlog.addPost(firstPost)
myBlog.addPost(secondPost)

Thanks

Upvotes: 0

Views: 1245

Answers (1)

sawa
sawa

Reputation: 168101

Initialize the variable as an array, not as a hash.

@post = []

Upvotes: 2

Related Questions