0

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

2
  • 1
    You want to create Array.. But you didn't give a small amount of time to read the Ruby Array API.. That's not good. :( Commented Apr 9, 2015 at 15:34
  • When reporting an exception that was raised, please give the offending line as well as all pertinent information in the exception message (though here it's obvious). Ruby newbies often don't give error messages the attention they deserve. In this case, it pinpoints the problem. You are invoking push on an instance of Hash (i.e, sending the method push to an instance of the class Hash). The error message says that the class Hash doesn't have an instance method push. Commented Apr 9, 2015 at 17:17

1 Answer 1

2

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

@post = []
Sign up to request clarification or add additional context in comments.

2 Comments

I just wrote same thing. ;)
Thanks, I am very new to Ruby.

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.