What type of PI, cos in Ruby

I want to ask about the type of PI and cos with Ruby. What is the convention for writing these types?

Can I write: Math::sin , Math::PI or Math.sin , Math.PI ?

+6
source share
5 answers
 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 
+8
source

PI is a constant that belongs to the Math module. Constants are accessed using the :: operator:

 Math::PI 

I believe that it is called a region resolution operator. It can also allow class methods, so you can definitely write:

 Math::sin 

A point operator sends messages to objects, which is a fancy way of saying that it calls methods. PI is a constant, so you cannot access it this way. Math.PI equivalent to Math.send :PI , which does not work, since Math does not respond_to? :PI respond_to? :PI . Of course you can fix this:

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

With method_missing you can even make it work with any constant:

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

Firstly, there is no Math.PI , it Math::PI - in this case use the one that really works.

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

sin , etc. are functions and may be available in any case. I use dot-notation, Math.sin(foo) because it is easier on the eyes (a matter of opinion) and it looks like canonically written Rails canonical code (like Rails ActiveRecord findAll , like User.findAll )) and like most of the other languages ​​that I use regularly do this.

Edit Oh, I may have misunderstood the question.

+1
source

If I ask the question correctly, you are asking for the type of value that cos returns. Instead of telling you what it is, I prefer to show you a way to test it for myself.

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

If you include Math in your code, you can simply write:

 PI cos(0.12) 

You need the Math prefix only if Math not enabled.

Have you tried using a gem wrapped around a Math module? Check out the gem math_calculator. This will allow you to write your expressions, for example. "4 * pi * cos (0.12)", etc.

0
source

Source: https://habr.com/ru/post/917790/


All Articles