Return object

D

Dmitry N Orlov

(Inspired by Test Driven Development of Kent Bek)
How Can I return from a class method object of the class ? Like this:
class Dollar
attr_reader :amount
def initialize(amount)
@amount = amount
end
def times(multiplier)
return Dollar.new(@amount * multiplier) #??????????
end
end
 
G

gabriele renzi

il Sun, 9 Nov 2003 09:37:42 +0500, "Dmitry N Orlov"
(Inspired by Test Driven Development of Kent Bek)
How Can I return from a class method object of the class ? Like this:
class Dollar
attr_reader :amount
def initialize(amount)
@amount = amount
end
def times(multiplier)
return Dollar.new(@amount * multiplier) #??????????
end
end

well, times is not a class method:NoMethodError: undefined method `times' for Dollar:Class
from (irb):10

and @amount is an instance variable:=> #<Dollar:0x2804178 @amount=100>

as you can see everything is fine :)
but probably you may want to use

def Dollar.times
....
end
or
def self.times
....
end
and @@amount ?
 
D

Dmitry N Orlov

I just want return object of the class from object-method times(). See
TDD, please, to understand me :)
 
D

Dmitry N Orlov

I just want return object of the class from object-method times(). See
TDD, please, to understand me :)
Sorry. It's fine

class Dollar
attr_reader :amount
def initialize(amount)
@amount = amount
end
def times(multiplier)
return Dollar.new(@amount * multiplier) #??????????
end
end

five = Dollar.new(5)
product = five.times(6)
#Now product is a Instance of Dollar
p product.inspect
p five.inspect
p (product.times(10).inspect)
p product.inspect
p five.inspect

#<Dollar:0x2787810 @amount=30>
#<Dollar:0x27878e8 @amount=5>
#<Dollar:0x2787750 @amount=300>
#<Dollar:0x2787810 @amount=30>
#<Dollar:0x27878e8 @amount=5>
 
G

gabriele renzi

il 10 Nov 2003 05:32:34 -0800, (e-mail address removed) (Dmitry N Orlov) ha
scritto::
Sorry. It's fine

well, I supposed this :)

BTW you don't need to do
p object.inspect
p object
is enough

Kernel#p calls argument#inspect by itself, that's what is for :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,139
Messages
2,570,805
Members
47,356
Latest member
Tommyhotly

Latest Threads

Top