Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the type of PI, cos in Ruby

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

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

like image 889
Mohammed Hajjaj Avatar asked Jun 11 '12 12:06

Mohammed Hajjaj


People also ask

What is Pi in Ruby?

Ruby - Math::PI Constant The Ruby Math::PI is the ratio of the a circle's circumference to its diameter. It is approximately 3.14159.

What is Math in Ruby?

Math module This gives you access to mathematic tools such as square root, sine, cosine, and tangent via Ruby methods. To access these in your code simply refer to the module Math and call the method on the module. For example, to get the square root of 9 you'd write Math. sqrt(9) .


3 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
like image 123
steenslag Avatar answered Sep 28 '22 22:09

steenslag


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

Math::PI

I believe it is called the scope resolution operator. It can also resolve to class methods, so you can definitely write:

Math::sin

The dot operator sends messages to objects, which is a fancy way of saying it calls methods. PI is a constant, so you can't access it that way. Math.PI is equivalent to Math.send :PI, which doesn't work since Math doesn't respond_to? :PI. Of course, you can fix that:

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
like image 25
Matheus Moreira Avatar answered Sep 30 '22 22:09

Matheus Moreira


First, there is no Math.PI, it's Math::PI--in this case, use the one that actually 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 accessed either way. I use dot-notation, Math.sin(foo), because it's easier on the eyes (matter of opinion), and similar to how other Rails code is canonically written (like Rails' ActiveRecord findAll, e.g., User.findAll), and how most other languages I use regularly do it.

Edit Oh, I may have misunderstood the question.

like image 36
Dave Newton Avatar answered Sep 30 '22 22:09

Dave Newton