# How to make 1+a work if a is not a numeric object?

I defined a to_i method for a, but it seems not work.

BTW, I do not want to override Fixnum’s + method.

Is it your belief that the only types that can appear on either side of
a + sign are Integers?

7stud – wrote in post #1014362:

Is it your belief that the only types that can appear on either side of
a + sign are Integers?

I just made my question simple. it actually could be either integer or
float.

Zd Yu wrote in post #1014364:

7stud – wrote in post #1014362:

Is it your belief that the only types that can appear on either side of
a + sign are Integers?

I just made my question simple. it actually could be either integer or
float.

class A
def to_i
10
end
end

a = A.new

result = 1 + a.to_i
puts result

–output:–
11

Works fine, all the time.

Peter Z. wrote in post #1014366:

class Numeric - RDoc Documentation

Thank you Peter! coerce is the right solution!

On Tue, 2 Aug 2011 15:15:10 +0900, Zd Yu wrote:

I defined a to_i method for a, but it seems not work.

BTW, I do not want to override Fixnum’s + method.

http://ruby-doc.org/core/classes/Numeric.html#M000959

For example:
ruby-1.9.2 :001 > class A
ruby-1.9.2 :002?> def coerce(other)
ruby-1.9.2 :003?> [other, 5]
ruby-1.9.2 :004?> end
ruby-1.9.2 :005?> end
=> nil
ruby-1.9.2 :006 > 1 + A.new
=> 6

Zd Yu wrote in post #1014372:

Peter Z. wrote in post #1014366:

class Numeric - RDoc Documentation

Thank you Peter! coerce is the right solution!

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

Kind regards

robert