To find the volume of a sphere in Ruby, we can use the formula V = (4/3) * π * r³, where V is the volume, π is the mathematical constant pi, and r is the radius of the sphere.
Here's the code:
main.rb255 chars10 lines
Output:
main.rb46 chars2 lines
In this code, we define a method called sphere_volume
that takes a radius argument and calculates the volume of the sphere using the formula. The Math::PI
constant is used to get the value of pi, and the **
operator is used to raise the radius to the power of 3. Finally, the calculated volume is returned from the method.
To use the method, we simply call it with a value for the radius and assign the returned volume to a variable. We can then output the result using puts
.
gistlibby LogSnag