PI的类型是什么,因为Ruby



我想问一下 PI 的类型以及 Ruby 的 cos。编写这些类型的约定是什么?

我可以这样写:Math::sinMath::PIMath.sinMath.PI吗?

puts Math::PI
#=> 3.141592653589793
include Math
puts PI.class
#=> Float
require "bigdecimal/math"
include BigMath
puts PI(50).class
#=> BigDecimal
puts PI(50)
#=> 0.3141592653589793238462643383279502884197169399375105820974944592309049629352442819E1

>PI是属于Math模块的常量。常量通过 :: 运算符访问:

Math::PI

我相信它被称为范围解析运算符。它也可以解析为类方法,所以你绝对可以写:

Math::sin

点运算符将消息发送到对象,这是一种奇特的说法,可以说它调用方法。 PI是一个常量,因此您无法以这种方式访问它。 Math.PI等同于Math.send :PI,这不起作用,因为Mathrespond_to? :PI。当然,您可以解决此问题:

def Math.PI
  Math::PI
end
Math.PI

使用 method_missing ,您甚至可以使其与任何常量一起工作:

def Math.method_missing(method, *arguments, &block)
  Math.const_get method, *arguments, &block
end
Math.PI
Math.E

首先,没有Math.PI,它是Math::PI - 在这种情况下,使用实际有效的那个。

[1] pry(main)> Math.PI
NoMethodError: undefined method `PI' for Math:Module
[2] pry(main)> Math::PI
=> 3.141592653589793

sin等是函数,可以通过任何一种方式访问。Math.sin(foo),我使用点符号,因为它更容易(意见问题),并且类似于其他Rails代码的规范编写方式(如Rails的ActiveRecord findAll,例如,User.findAll),以及我经常使用的大多数其他语言。

编辑 哦,我可能误解了这个问题。

如果我

答对了你的问题,你问的是cos返回的值的类型。与其告诉你它是什么,我更愿意告诉你一种自己检查它的方法。

irb(main):003:0>Math::cos(0.2).class
=> Float
irb(main):004:0> Math::PI.class
=> Float

如果你include Math你的代码,那么你只需编写:

PI
cos(0.12)

仅当不包含Math时,才需要为Math前缀。

您是否尝试过使用包裹在数学模块周围的宝石?查看math_calculator宝石。这将允许您正常编写表达式,例如。"4*pi*cos(0.12)"等。

相关内容

最新更新