Created
October 21, 2009 06:08
-
-
Save udzura/214910 to your computer and use it in GitHub Desktop.
explaining oneliner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hyphenize_numbers2_ *args | |
puts args. #=> [1, 2, 3, 5, 6, 7, 8, 9, 12, 14] | |
map{|v| v.to_i}. # Integerにキャスト | |
sort. # 整列 | |
uniq. # 重複いらないので削除 | |
unshift(nil).#=> [nil, 1, 2, 3, 5, 6, 7, 8, 9, 12, 14] | |
enum_for(:each_cons, 2). | |
# [[nil, 1],[1, 2],[2, 3],..., [9, 12],[12, 14]] で each | |
# enum_cons(2). でもいいよね | |
inject([]){|dst, src| | |
# argsを連続する数値ごとにグルーピングし、dst=[]に格納 | |
dst.push( | |
# Enumerable#inject は、最後に評価したブロックの | |
# 返り値を返すので、ブロック内ではかならずdstが返るようにArray#pushを用いる | |
(!src[0] || src[1] - src[0] > 1) ? | |
# 最初の値(先頭nilで判断)であるか、または n-1 番目と n 番目の差が2以上なら | |
[src[1]] : # 新しい配列を生成して突っ込む | |
dst.pop.push(src[1]) # それ以外(連続する値)は、最後の配列に値を加える | |
# ミソは、いったんdstから最後の値をpopしてしまって、同じpushメソッドで突っ込んでる | |
) | |
}.#=> [[1, 2, 3], [5, 6, 7, 8, 9], [12], [14]] | |
map{|nums| # 連続する値にハイフン付加 | |
nums.length == 1 ? | |
nums[0].to_s : # 一つしか連続していないならハイフン不要 | |
"#{nums.first}-#{nums.last}" # #{最初}-#{最後} | |
}.#=> ["1-3", "5-9", "12", "14"] | |
join(", ") + "." # カンマでjoin、最後にピリオド | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment