如何在Ruby on Rails中向Math类动态添加方法?

时间:2021-07-22 06:53:50

I am trying to add the following method to the Math class in Ruby on Rails:

我试图将以下方法添加到Ruby on Rails中的Math类:

class Math
  def self.round_with_precision(number, precision)
    scalar = 10.0 ** precision
    number = number * scalar
    number = number.round
    number = number / scalar
    return number;
  end
end

I then added the following to my environment.rb:

然后我将以下内容添加到我的environment.rb中:

require 'lib/math'

When I open up the Rails console I get the following error: './lib/math.rb:2:TypeError Math is not a class'

当我打开Rails控制台时,我收到以下错误:'。/ lib / math.rb:2:TypeError Math不是一个类'

It seems like I'm overlooking something very simple.

好像我忽略了一些非常简单的东西。

Any thoughts?

Thanks in advance for your help.

在此先感谢您的帮助。

3 个解决方案

#1


Math is a module, just rename class to module.

Math是一个模块,只需将类重命名为module。

#2


You can place the file containing this code in config/initializers and it will automatically be included. ~ Just a FYI.

您可以将包含此代码的文件放在config / initializers中,它将自动包含在内。 〜只是一个FYI。

#3


If you use instance_eval, you don't have to worry about whether to use class or module:

如果使用instance_eval,则不必担心是使用类还是模块:

Math.instance_eval do
  def round_with_precision(number, precision)
    scalar = 10.0 ** precision
    (number * scalar).round / scalar
  end
end

#1


Math is a module, just rename class to module.

Math是一个模块,只需将类重命名为module。

#2


You can place the file containing this code in config/initializers and it will automatically be included. ~ Just a FYI.

您可以将包含此代码的文件放在config / initializers中,它将自动包含在内。 〜只是一个FYI。

#3


If you use instance_eval, you don't have to worry about whether to use class or module:

如果使用instance_eval,则不必担心是使用类还是模块:

Math.instance_eval do
  def round_with_precision(number, precision)
    scalar = 10.0 ** precision
    (number * scalar).round / scalar
  end
end