DAY 10
0

## 誰比誰長，迴圈和 reduce 用法，Ruby 30 天刷題修行篇第十話

（題目來源：Codewars

You are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

Examples:

strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2

Concatenate the consecutive strings of strarr by 2, we get:

treefoling   (length 10)  concatenation of strarr[0] and strarr[1]
folingtrashy ("      12)  concatenation of strarr[1] and strarr[2]
trashyblue   ("      10)  concatenation of strarr[2] and strarr[3]
blueabcdef   ("      10)  concatenation of strarr[3] and strarr[4]
abcdefuvwxyz ("      12)  concatenation of strarr[4] and strarr[5]

Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
The first that came is "folingtrashy" so
longest_consec(strarr, 2) should return "folingtrashy".

In the same way:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"

n being the length of the string array, if n = 0 or k > n or k <= 0 return "".

Note
consecutive strings : follow one after another without an interruption

def longest_consec(strarr, k)
if strarr.length == 0 || k <= 0 || k > strarr.length
""
else
arr = []
i = 0
while i < (strarr.length - k) + 1
arr[i] = strarr.slice(i, k).join("")
i += 1
end
arr.reduce { |memo, word| memo.length >= word.length ? memo : word }
end
end

while i < (strarr.length - k) + 1
#do something
i += 1
end

def longest_consec(strarr, k)
return "" unless k.between?(1, strarr.length)
strarr.each_cons(k).map(&:join).max_by(&:length) || ""
end

Ｗow，第一行就用了我沒看過的 between? 方法，不過字面上的意義很好懂，這裡就不深入分析了。而下一行也是讓人眼花撩亂，有兩個沒看過的方法，大哥你是把整本手冊都背起來了嗎？只能先查一下手冊

1.each_cons 方法，帶入 ａ，就可以從 Enumerable 迭代取出長度為 a 的值，簡直是為這題量身打造，直接看官網範例：

(1..10).each_cons(3) { |a| p a }
# outputs below
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]

1. &: 寫法，還原就是 map{|el| el.join("")} ，這部分可以等日後再談。
2. max_by，返回 Enumerable 中最大值，這裡是 length。