I am a newbie to Ruby and am learning it using “Programming Ruby 1.9” (PickAxe). In the book, I see a program which I modified thus:
1 #!/usr/bin/env ruby -w
2
3 class BookInStock
4 attr_reader :isbn
5 attr_accessor :price
6 def initialize(isbn, price)
7 @isbn = isbn
8 @price = Float(price)
9 end
10 # def price=(price)
11 # @price = Float(price)
12 # end
13 end
14
15 b1 = BookInStock.new("isbn1", 3)
16 p b1
17 b2 = BookInStock.new("isbn2", 3.14)
18 p b2
19 b3 = BookInStock.new("isbn3", "5.67")
20 p b3
21 b3.price = "10.32"
22 p b3
Line number 8 ensures that the right value is assigned to b3.price.
But how do I handle cases like line number 21 without using a method like in line 10-12?
Is there some way in which I can modify the attr_accessor for this? Or am I asking for too much 😀
I could not find any such references online.
attr_accessor :symis a method of a Class that defines simple getter and setter methods.You can define your own
casting_attr_accessor:And then in your class use it like