Forum: Ruby Ruby Class Help

75eb775a3636c4dbc0c305ae3682df31?d=identicon&s=25 Rocky D. (rocky_d)
on 2013-09-12 07:32
Hello. I'm Ruby beginner, I'm not getting proper output, of course it's
problem in my code not in Ruby itself.
Anyone can help to fix this?

The out put should be:
The Dark Knight Rises | Release Date: 2013 | Rating: 7.
But I'm also getting this "#<Movie:0x102b26620>" thing. Anyone can help
me why this is coming even after I used "to_s" ? your help will be
appreciated.
===============

class Movie
  def initialize(title, date, rating)
  @title = title
  @date = date
  @rating = rating
  end

  def to_s
    puts "Name: #{@title} | Release Date: #{@date} | Rating:
#{@rating}."
  end

  def thumbs_up
    @rating += @rating
  end

  def thumbs_down
    @rating -= @rating
  end

end

TheDarkKnight = Movie.new("The Dark Knight Rises", 2013, 7)

puts TheDarkKnight
====================
3853dd5371ac1e094fc45d6c2aa0e459?d=identicon&s=25 Carlo E. Prelz (Guest)
on 2013-09-12 07:45
(Received via mailing list)
Subject: Ruby Class Help
  Date: gio 12 set 13 07:32:25 +0200

Quoting Rocky D. (lists@ruby-forum.com):

> Hello. I'm Ruby beginner, I'm not getting proper output, of course it's
> problem in my code not in Ruby itself.
> Anyone can help to fix this?

to_s must *return* the string, not print it out.

Just remove the 'puts'.

Carlo
75eb775a3636c4dbc0c305ae3682df31?d=identicon&s=25 Rocky D. (rocky_d)
on 2013-09-12 07:58
Carlo E. Prelz wrote in post #1121238:
> Subject: Ruby Class Help
>   Date: gio 12 set 13 07:32:25 +0200
>
> Quoting Rocky D. (lists@ruby-forum.com):
>
>> Hello. I'm Ruby beginner, I'm not getting proper output, of course it's
>> problem in my code not in Ruby itself.
>> Anyone can help to fix this?
>
> to_s must *return* the string, not print it out.
>
> Just remove the 'puts'.
>
> Carlo


Yes, removed 'puts' and problem solved! Another thing I was doing wrong
was using "@rating += @rating" I've no idea why did I wrote that! it
should be "@rating += 1" :) same for thumbs down method.
Thank you Carlo for help :)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.