Please help me quick

a have two object a(@a=3 @b=4 @c=5)
b (@a=5,@b=5 @=6)

How can I do a+b, the addition of two object…

On Thu, Feb 9, 2012 at 2:25 PM, luk malcik [email protected] wrote:

a have two object a(@a=3 @b=4 @c=5)
b (@a=5,@b=5 @=6)

How can I do a+b, the addition of two object…

~$ irb
1.9.3-p0 :001 > class A
1.9.3-p0 :002?> attr_accessor :a
1.9.3-p0 :003?> end
=> nil
1.9.3-p0 :004 > a = A.new
=> #<A:0x93fd320>
1.9.3-p0 :005 > b = A.new
=> #<A:0x93f77e0>
1.9.3-p0 :006 > a.a
=> nil
1.9.3-p0 :007 > b.a
=> nil
1.9.3-p0 :008 > class A
1.9.3-p0 :009?> def +(other)
1.9.3-p0 :010?> result = A.new
1.9.3-p0 :011?> result.a = self.a + other.a
1.9.3-p0 :012?> result
1.9.3-p0 :013?> end
1.9.3-p0 :014?> end
=> nil
1.9.3-p0 :015 > a.a = 10
=> 10
1.9.3-p0 :016 > b.a = 15
=> 15
1.9.3-p0 :017 > a+b
=> #<A:0x93badb8 @a=25>

I’ll leave it to you to extend this to your specific use case.

HTH,

Peter

*** Available for a new project ***

Peter V.
http://twitter.com/peter_v
http://rails.vandenabeele.com
http://coderwall.com/peter_v

THANK YOU!! It’s really helpfully:)

On Thu, Feb 9, 2012 at 2:25 PM, luk malcik [email protected] wrote:

a have two object a(@a=3 @b=4 @c=5)
b (@a=5,@b=5 @=6)

How can I do a+b, the addition of two object…

http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs