ruby Unit Test problem
Have been trying to get the following code to work, but can't; it says I'm calling a private method.
What am I doing wrong?
def subtotal(price, qty = 1)
return nil if price.to_f<= 0 || qty.to_f <= 0
price.to_f * qty.to_f
end
puts subtotal(12.93)
puts subtotal(12.93, 3)
puts subtotal(456.82, 6)
def subtotal(qty = 1)
return nil if price.to_f<= 0 || qty.to_f <= 0
self.to_f * qty.to_f
end
开发者_如何学Gobook = 39.99
car = 16789
puts book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
Though I'd like more information, like the full class definition and the error trace, since the public method to_f
is the only other method call here, I'm guessing that subtotal
is defined as a private method.
In a Ruby class definition, keywords like public
, protected
, and private
apply to all methods that come after the keyword. Check that the subtotal
definition is not below private
or protected
in the class definition.
If not, then the issue likely lies elsewhere. Check that error trace, and look at where the error actually comes from.
Your subtotal works in two different environments.
One time, its a 'stand alone method', the other time it's a Numeric-method. So, lets define them as Numeric-method:
def subtotal(price, qty = 1)
return nil if price <= 0 || qty <= 0
price * qty
end
class Numeric
def subtotal(qty = 1) #only one paramter. The other is 'self'
return nil if self <= 0 || qty <= 0
self * qty
end
end
puts subtotal(12.93)
puts subtotal(12.93, 3)
puts subtotal(456.82, 6)
book = 39.99
car = 16789
puts book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
Remark on my code: I don't see a real reason for converting to Floats. If you start with Fixnums (see your car-example), then my solution works also. Perhaps, you need the conversion for your specific case.
From your example code I would prefer to define a Articcle class:
def subtotal(price, qty = 1)
return nil if price <= 0 || qty <= 0
price * qty
end
class Article
def initialize(price = 0)
@price = price
end
def subtotal(qty = 1)
return nil if @price <= 0 || qty <= 0
@price * qty
end
end
puts subtotal(12.93)
puts subtotal(12.93, 3)
puts subtotal(456.82, 6)
book = Article.new(39.99)
car = Article.new(16789)
puts book.subtotal(3)
puts car.subtotal
puts car.subtotal(7)
精彩评论