I defined a to_i method for a, but it seems not work.
BTW, I do not want to override Fixnum's + method.
···
--
Posted via http://www.ruby-forum.com/.
I defined a to_i method for a, but it seems not work.
BTW, I do not want to override Fixnum's + method.
--
Posted via http://www.ruby-forum.com/.
Is it your belief that the only types that can appear on either side of
a + sign are Integers?
--
Posted via http://www.ruby-forum.com/.
Numeric#coerce is your friend:
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
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.
--
WBR, Peter Zotov.
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.
--
Posted via http://www.ruby-forum.com/\.
Peter Zotov wrote in post #1014366:
Numeric#coerce is your friend:
class Numeric - RDoc Documentation
Thank you Peter! coerce is the right solution!
--
Posted via http://www.ruby-forum.com/\.
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.
--
Posted via http://www.ruby-forum.com/\.
Zd Yu wrote in post #1014372:
Peter Zotov wrote in post #1014366:
Numeric#coerce is your friend:
class Numeric - RDoc DocumentationThank you Peter! coerce is the right solution!
You can find more info on this here:
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html
Kind regards
robert
--
Posted via http://www.ruby-forum.com/\.