Your code works! Good job!
Here are some notes from me:
- I like the attribute naming on your
postobject, and the cleanness of youradd_commentsmethod, and the utilization of ato_smethod on yourpostobject, and the use of anargshash for yourinitializearguments, and the cleanness of your encapsulating yourcommentobjects inside yourpostobject. Well done! - One of the attribute names on your
commentclass is a little redundant:comment.user_comment. Since we already know this is an attribute of acomment, we can name it something likecomment.textorcomment.content. (This attribute is thetextorcontentof thecomment. To say that it is theuser_commentof thecommentis too vague and redundant.) - A lot of your runner code is not really running anything but rather parsing data and then setting up that data for your object
newmethods. It would be better if this parsing were occuring in a class or, even better, in a module. Then the runner code would simply call that parser module. (You want your runner code to do only one thing: run code. The actual work should be done inside your classes and modules.)
##Some tips on using to_s##
Nice use of to_s on your post object! Note though: If you call puts on an object (for example: puts post), Ruby will automatically puts the return value of that object's to_s method. (Thus, there is no need to have any puts calls inside your to_s method.) Because of this, you could refactor your post object's current to_s method into something like this:
def to_s
array_of_comment_strings = @comments.map do |comment|
"#{comment.user_comment}\n\n-#{comment.user_id}\n\n"
end
"#{title} (Hacker News ID: #{item_id})\nURL: #{url}\nAuthor: #{author_username}\nPoints: #{points}\n\nComments:\n" + array_of_comment_strings.join("\n")
endOr, even better, you could also write a to_s method for your comment objects, and call that to_s method in your post object's to_s method. So you could write a to_s for your comment objects like this:
def to_s
"#{user_comment}\n\n-#{user_id}\n\n"
endAnd then call that to_s from within your post to_s, so that your post to_s would now look like this:
def to_s
array_of_comment_strings = @comments.map do |comment|
comment.to_s
end
"#{title} (Hacker News ID: #{item_id})\nURL: #{url}\nAuthor: #{author_username}\nPoints: #{points}\n\nComments:\n" + array_of_comment_strings.join("\n")
endThis way, each of your classes has its own to_s method, which is much cleaner than only one class having a to_s method.
Also note: Because puts post will puts the return value of the post to_s method, you can change the last line of your runner code to simply:
puts postI hope this helps. Any questions let me know. -Phil