find the volume of a sphere in ruby

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.rb
def sphere_volume(radius)
  volume = (4.0 / 3.0) * Math::PI * radius ** 3
  return volume
end

# Example usage: Find the volume of a sphere with radius 5
sphere_radius = 5
volume = sphere_volume(sphere_radius)
puts "The volume of the sphere is #{volume}"
255 chars
10 lines

Output:

main.rb
The volume of the sphere is 523.5987755982989
46 chars
2 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