Skip to content

Instantly share code, notes, and snippets.

@jdx
Last active December 18, 2015 08:29
Show Gist options
  • Save jdx/5754301 to your computer and use it in GitHub Desktop.
Save jdx/5754301 to your computer and use it in GitHub Desktop.
consecutive numbers?
def consecutive?(array)
array.each_with_index.all? { |a, i| a+1 == a[i+1] }
end
def to_consecutive(array)
if consecutive?(array)
"#{array.first}-#{array.last}"
else
array.to_sentence
end
end
to_consecutive [1,2,3] #=> 1-3
to_consecutive [1,2,4] #=> 1, 2, and 4
to_consecutive [1] #=> 1
to_consecutive [1,3] #=> 1 and 3
to_consecutive [1,2,3,5] #=> 1, 2, 3, and 5
@erkattak
Copy link

  def to_consecutive(array)
    case array.size
    when 0 then ""
    when 1 then "#{array[0]}"
    else
      if (array[0]..array[-1]).inject { |s,x| s + x } == array.inject { |s,x| s + x }
        "#{array[0]}-#{array[-1]}"
      else
        array.to_sentence
      end
    end
  end

this handles empty, one and two item arrays, and more ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment