To find the nth triangular number in Ruby, we can either use a loop or a formula.
Using a loop:
main.rb122 chars10 linesUsing a formula:
main.rb86 chars6 linesBoth functions take one argument n, which represents the index of the triangular number we want to find. The first function (triangular_loop) loops through the numbers from 1 up to n, adding each number to a sum. The second function (triangular_formula) uses a formula to calculate the triangular number directly.
Both functions return the nth triangular number. In this example, calling either function with an argument of 5 will return 15, which is the 5th triangular number.
gistlibby LogSnag