學習
-
include? 方法:當我們要找出字串中是否有包含某字元,這樣相對簡單的判斷在 ruby 直接提供「include?」方法 - String.include? string (範例: "rzchen".include? "rz" 會回傳 true)
-
any? 接 block 的用法:any? 可以用來看 Array 中是否有內容物,以這次 best practice 就有提到後面再加上 {|n| n.include?("a")} 就可以變成進階搜尋的概念,array.any? { |n| n.includes?("a")} 翻譯成中文就是「array 中的任何內容物是否有包含 a 字元」
題目:
Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
#Example 1: a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]
#Example 2: a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
# 翻譯:題目會給你兩個 array,拿第一個 array 內所有字串到第二個 array 去比對,找出比對後有符合的,最後回傳以 a-z 排序後的陣列
答案需要過以下測試:
RSpec.describe do
it "test1" do
a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
expect(in_array(a1, a2)).to eq(["arp", "live", "strong"])
end
it "test2" do
a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
expect(in_array(a1, a2)).to eq([])
end
end
我的答案
def in_array(array1, array2)
result = []
array2.each do |a2|
array1.each do |a1|
if a2.include? a1
result << a1
end
end
end
result.uniq.sort
end
思路:
- 一開始想說先排序再去用 Regex,後來發現完全不是如此
- 找字串中是否有特定字元可以用 include? 透過 兩個 each 去判斷,符合的塞進去一個陣列
- 最後發現會有重複的值也沒排序,再用 uniq 與 sort
Best practice in Codewars
def in_array(array1, array2)
array1.select{|s| array2.any?{|w| w.include?(s) } }.sort
end