James Herdman
4/12/2006 4:05:00 AM
> class X
> attr_reader :text
> def initialize
> @name = 'X'
> @text = ""
> end
> def add_to_text( p_str )
> @text += p_str
> end
> end
>
> class Y < X
> def initialize
> super
> @name = 'Y'
> @arr = Array.new
> end
> def Y.from_x( p_X )
> l_rslt = Y.new
> l_rslt.text = p_X.text
> end
>
> private
> def text=( p_text )
> @text = p_text
> end
> end
>
> x = X.new
> y = Y.from_a( a )
>
> exit 0
I can't proporte to be a Ruby expert, but I'll give it my best shot.
First of all, I'm a bit confused by what you're hoping the effect of
Y.from_x() is. Are you hoping to return a new object of type Y? If
I'm not mistaken, you may need to explicitly return it. i.e.
def Y.from_x( p_X )
result = Y.new
result.text = p_X.text
return result
end
Now, the second line of this method is where I think your problem might
be. When I run your code, as is, in IRB, it freaks out. result.text
is calling the private method text(). Since private methods CANNOT be
invoked by an explicit receiver, you are violating this by saying
result.text(). Try removing the private condition, and I think you'll
be okay.
This is your new Y
class Y < X
def initialize
super
@name = 'Y'
@arr = Array.new
end
def Y.from_x( p_X )
l_rslt = Y.new
l_rslt.text = p_X.text
return l_rslt
end
def text=( p_text )
@text = p_text
end
end
irb(main):028:0> x = X.new
=> #<X:0x353b10 @text="", @name="X">
irb(main):029:0> x.add_to_text("It works!")
=> "It works!"
irb(main):030:0> x.text
=> "It works!"
irb(main):031:0> y = Y.from_x(x)
=> #<Y:0x32cce0 @arr=[], @text="It works!", @name="Y">
irb(main):032:0> y.text
=> "It works!"
There ya go! =)
I hope this helps,
James H.
PS: The only thing some of the more experience people might suggest is
that you consider giving your variable names a more English-like
naming. For example, "l_rslt" into "result", or "p_X" into "source_x".
Ruby is very English-like in syntax, why not keep with the trend? It
makes it easier to read your code, and faster to understand what's
going on after you leave it for a while.