DEV Community

loading...

Discussion on: Daily Challenge #12 - Next Larger Number

Collapse
kaspermeyer profile image
Kasper Meyer

Ruby solution

Trying out Object#then, which was introduced recently in Ruby 2.6, just for the fun of it.

require "minitest/autorun"

class NextBiggerNumber
  def self.from number
    number.to_s.split('')
      .then { |result| result.permutation }
      .then { |result| result.map(&:join) }
      .then { |result| result.map(&:to_i) }
      .then { |result| result.sort }
      .then { |result| result[result.index(number) + 1] }
  end
end

class NextBiggerNumberTest < MiniTest::Test
  def test_next_bigger_number_with_two_digits
    assert_equal 21, NextBiggerNumber.from(12)
  end

  def test_next_bigger_number_with_three_digits
    assert_equal 531, NextBiggerNumber.from(513)
  end

  def test_next_bigger_number_with_four_digits
    assert_equal 2091, NextBiggerNumber.from(2019)
  end
end