How to get the volume of a cube in Ruby
Overview
The volume of an object is the total space occupied by that object. The volume of a cube is obtained by taking the product of three lengths of the cube.
Syntax
volume = s * s * s
Syntax to obtain the volume of a cube in Ruby
Parameters
volume: This represents the volume of the cube.s: This represents the length of each side of the cube.
Return value
- The value returned is the volume of the cube.
Example
# create function to get the volume of a cubedef getVolume(lengthOfSide)volume = lengthOfSide * lengthOfSide * lengthOfSideputs "The volume of cube with length of side #{lengthOfSide} is = #{volume}"end# create length of sides of cubesl1 = 23l2 = 5l3 = 0.5l4 = 100# get the volumes of the cubesgetVolume(l1)getVolume(l2)getVolume(l3)getVolume(l4)
Explanation
- Line 2: We create a function called
getVolume(), which takes the length of the side of a cube, calculates the volume, and prints the result to the console. - Lines 9–12: We provide several values for the lengths of sides of different cubes whose volume we want to get.
- Lines 15–18: We invoke the function created to get the volume of the cubes.