find the nth hexagonal number in ruby

To find the nth hexagonal number in Ruby, we can use the formula:

Hexagonal number = n(2n-1)

We can create a method that takes the nth value as an argument and calculates and returns the hexagonal number. Here is the implementation:

main.rb
def hexagonal_number(n)
  hexagonal_num = n*(2*n-1)
  return hexagonal_num
end
79 chars
5 lines

Now we can call this method and pass the nth value as an argument to find the corresponding hexagonal number:

main.rb
nth_value = 5
hexagonal_num = hexagonal_number(nth_value)
puts "The #{nth_value}th hexagonal number is #{hexagonal_num}."
122 chars
4 lines

Output:

main.rb
The 5th hexagonal number is 85.
32 chars
2 lines

In the above example, we passed 5 as the nth value and the program returned 85 as the corresponding hexagonal number.

gistlibby LogSnag