Forum: Ruby see what happens in the following code?

Bf22916bd708818754c708a2355db55d?d=identicon&s=25 Oscar Oscar (oscarmeza)
on 2016-11-25 02:34
see what happens in the following code ????

class BookInStock

  # attr_reader   :isbn
  attr_accessor :price , :isbn

  def initialize(isbn, price)
    @isbn  = isbn
    @price = Float(price)
  end

  def price_in_cents
    Integer(price*100 + 0.5) + @price
  end

  def price_in_cents=(cents)
    puts price
    price = cents / 100.0 + price
    puts price
    p price
    @price = price
  end
  def imp
     puts "ISBN = #{isbn}"
     end
  # ...
end
book = BookInStock.new("isbn1", 33.80)
puts "Price          = #{book.price}"
puts "Price in cents = #{book.price_in_cents}"
book.price_in_cents = 1234
puts "Price          = #{book.price}"
puts "Price in cents = #{book.price_in_cents}"
book.imp
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2016-11-26 15:51
I changed your code a bit.


class BookInStock

  # attr_reader   :isbn
  attr_accessor :price , :isbn

  def initialize(isbn, price)
    @isbn  = isbn
    @price = Float(price)
  end

  def price_in_cents
    Integer(price*100 + 0.5) + @price
  end

  def price_in_cents=(cents)
    puts price
    price = cents.to_f / 100.0 + price.to_f
    puts price
    p price
    @price = price
  end
  def imp
     puts "ISBN = #{isbn}"
  end
  # ...
end

book = BookInStock.new("isbn1", 33.80)
puts "Price          = #{book.price}"
puts "Price in cents = #{book.price_in_cents}"
book.price_in_cents = 1234
puts "Price          = #{book.price}"
puts "Price in cents = #{book.price_in_cents}"
book.imp

You had a nil. Either in cents or in price variable.

Also you use a local variable called price and an
accessor method price for @price.

Are you sure that this does not confuse you?

It would confuse me. Whenever I would write code
that is complex for my brain to understand, then
by definition I classify it as wrong and simplify
the code. This is just how my brain works, it is
so lazy that it does not ever want to guess.
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.