[英]Ruby array of strings: split into smallest pieces
我想知道Ruby中是否有一個方法可以在最小的部分中拆分一個String
Array
。 考慮:
['Cheese crayon', 'horse', 'elephant ab c']
有沒有一種方法可以將其轉化為:
['Cheese', 'crayon', 'horse', 'elephant', 'a', 'b', 'c']
p ['Cheese crayon', 'horse', 'elephant a b c'].flat_map(&:split)
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]
我不知道。 但是您可以單獨拆分每個字符串,然后將結果展平為單個數組:
p ['Cheese crayon', 'horse', 'elephant a b c'].map(&:split).flatten
你可以這樣做:
array.map { |s| s.split(/\s+/) }.flatten
這會將您的字符串拆分為任意數量的空白字符。 據我所知,這是split
的默認行為,沒有任何參數,所以你可以將它縮短為:
array.map(&:split).flatten
['Cheese crayon', 'horse', 'elephant a b c'].join(' ').split
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.