Problem with modules and classes: undefined method
-
Need help on this problem, please:
[pre:25n9k511]module TEST
class Numeric
def precision(pre)
return self.truncate if pre == 0
mult = 10.0 ** pre
(self * mult).round.to_f / multend
end
a=123.4567
c= a.precision(2)
end #module[/pre:25n9k511]
getting the following error: "undefined method `precision' for 123.4567:Float"your help is very much appreciated
Thanks
-
@sonjachr said:
Need help on this problem, please:
[pre:19bvdgse]module TEST
class Numeric
def precision(pre)
return self.truncate if pre == 0
mult = 10.0 ** pre
(self * mult).round.to_f / multend
end
a=123.4567
c= a.precision(2)
end #module[/pre:19bvdgse]
getting the following error: "undefined method `precision' for 123.4567:Float"your help is very much appreciated
Thanks
Your code creates a new class TEST::Numeric that is independent of the buitin class Numeric because it is within the TEST module namespace. Float inherits from the builtin, not from your class.
That answered, it is generally considered very bad practice to modify builtin classes. You have no way to be sure that your patch won't collide with someone else's or break their code. Why not just use c=a.round(pre) ?
-
thanks for the quick answer. Unfortunately the c=round(pre) is not working for Sketchup2013 (wrong number of arguments (1 for 0)), it is only working for Sketchup2014.
It is my understanding, that I have to include the class in my root Namespace to get my Extension included in the Sketchucation warehouse. It is the only class I am having problems with.
I really need help on this.
Thanks
-
@sonjachr said:
thanks for the quick answer. Unfortunately the c=round(pre) is not working for Sketchup2013 (wrong number of arguments (1 for 0)), it is only working for Sketchup2014.
It is my understanding, that I have to include the class in my root Namespace to get my Extension included in the Sketchucation warehouse. It is the only class I am having problems with.
I really need help on this.
Thanks
Oh yeah, I forgot that the argument to Float#round was added as of 1.9, so that won't work prior to SU 2014. Seems that you have two possible ways to go to remain portable to 1.8 and obey the "no monkey-patching" rule:
-
Define your own class and use that instead of the builtin Float. This can be a pain, since it is easy to forget and write a=1.23 instead of a=TEST::MyFloat.new(1.23).
-
Do the less object-oriented way and define a function in your module that does what you wrote, but takes both the Float and pre as arguments. Then use c=TEST::precision(a, pre). Sort of like this:
module TEST def self.precision(f, pre) # probably should validate arg types and values here... return f.round if pre==0 ((f * 10**pre).round.to_f )/ 10**pre end end
-
-
**It works!**Thanks a lot, you saved my weekend!
Advertisement