How to get the Nth digit of a number in Ruby

1 Answer

0 votes
# Returns the N-th digit of a number counting from the left.
#
# Examples:
#   get_nth_digit_from_left(12345, 1) # => 1
#   get_nth_digit_from_left(12345, 3) # => 3
def get_nth_digit_from_left(input_number, digit_position)
  digit_string = input_number.abs.to_s

  if digit_position < 1 || digit_position > digit_string.length
    raise ArgumentError, "Digit position is out of range."
  end

  digit_string[digit_position - 1].to_i
end

# Program entry point.
def main
  input_number = 82_746

  first_digit = get_nth_digit_from_left(input_number, 1)
  third_digit = get_nth_digit_from_left(input_number, 3)
  fifth_digit = get_nth_digit_from_left(input_number, 5)

  puts "Number: #{input_number}"
  puts "1st digit from left: #{first_digit}"
  puts "3rd digit from left: #{third_digit}"
  puts "5th digit from left: #{fifth_digit}"
end

main


# run:
#
# Number: 82746
# 1st digit from left: 8
# 3rd digit from left: 7
# 5th digit from left: 6
#

 



answered 18 hours ago by avibootz
...