Ruby字符串数组:分割成最小的部分

时间:2022-01-22 21:39:21

I would like to know if there is a method in Ruby that splits an Array of String in smallest pieces. Consider:

我想知道Ruby中是否有一个方法可以将字符串数组分割成最小的部分。考虑:

['Cheese crayon', 'horse', 'elephant a b c']

(“奶酪蜡笔”、“马”、“大象b c”)

Is there a method that turns this into:

有没有一种方法可以把这变成:

['Cheese', 'crayon', 'horse', 'elephant', 'a', 'b', 'c']

[“奶酪”,“蜡笔”,“马”,“象”,“,“b”,“c”)

4 个解决方案

#1


7  

p ['Cheese crayon', 'horse', 'elephant a b c'].flat_map(&:split)
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]

#2


4  

None that I know of. But you can split each string individually and then flatten the results into a single array:

我不知道。但是你可以将每个字符串单独分开,然后将结果平摊到一个数组中:

p ['Cheese crayon', 'horse', 'elephant a b c'].map(&:split).flatten

#3


1  

You can do it this way:

你可以这样做:

array.map { |s| s.split(/\s+/) }.flatten

This splits your string by any number of whitespace characters. As far as I know, it's the default behavior of split without any arguments, so you can shorten it to:

这将字符串分割为任意数量的空格字符。据我所知,这是分割的默认行为,没有任何参数,所以可以缩短为:

array.map(&:split).flatten

#4


1  

['Cheese crayon', 'horse', 'elephant a b c'].join(' ').split
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]

#1


7  

p ['Cheese crayon', 'horse', 'elephant a b c'].flat_map(&:split)
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]

#2


4  

None that I know of. But you can split each string individually and then flatten the results into a single array:

我不知道。但是你可以将每个字符串单独分开,然后将结果平摊到一个数组中:

p ['Cheese crayon', 'horse', 'elephant a b c'].map(&:split).flatten

#3


1  

You can do it this way:

你可以这样做:

array.map { |s| s.split(/\s+/) }.flatten

This splits your string by any number of whitespace characters. As far as I know, it's the default behavior of split without any arguments, so you can shorten it to:

这将字符串分割为任意数量的空格字符。据我所知,这是分割的默认行为,没有任何参数,所以可以缩短为:

array.map(&:split).flatten

#4


1  

['Cheese crayon', 'horse', 'elephant a b c'].join(' ').split
# => ["Cheese", "crayon", "horse", "elephant", "a", "b", "c"]