简体   繁体   English

通过匹配将字符串分开创建的子字符串的构建列表

[英]Build list of substrings created by separating a string by a match

I have a string: 我有一个字符串:

"a_b_c_d_e"

I would like to build a list of substrings that result from removing everything after a single "_" from the string. 我想建立一个子字符串列表,该子字符串是从字符串中删除单个"_"后的所有内容所导致的。 The resulting list would look like: 结果列表如下所示:

['a_b_c_d', 'a_b_c', 'a_b', 'a']

What is the most rubyish way to achieve this? 实现这一目标的最红宝石方法是什么?

s = "a_b_c_d_e"
a = []
s.scan("_"){a << $`}                                                            #`
a # => ["a", "a_b", "a_b_c", "a_b_c_d"]

You can split the string on the underscore character into an Array . 您可以split下划线字符上的字符串splitArray Then discard the last element of the array and collect the remaining elements in another array joined by underscores. 然后丢弃该数组的最后一个元素,并将其余元素收集在下划线连接的另一个数组中。 Like this: 像这样:

str = "a_b_c_d_e"
str_ary = str.split("_") # will yield ["a","b","c","d","e"]
str_ary.pop # throw out the last element in str_ary
result_ary = [] # an empty array where you will collect your results
until str_ary.empty?
  result_ary << str_ary.join("_") #collect the remaining elements of str_ary joined by underscores
  str_ary.pop
end

# result_ary = ["a_b_c_d","a_b_c","a_b","a"]

Hope this helps. 希望这可以帮助。

I am not sure about “most rubyish”, my solutions would be: 我不确定“最红宝石”,我的解决方案是:

str = 'a_b_c_d_e'

(items = str.split('_')).map.with_index do |_, i| 
  items.take(i + 1).join('_')
end.reverse
########################################################
(items = str.split('_')).size.downto(1).map do |e|
  items.take(e).join('_')
end
########################################################
str.split('_').inject([]) do |memo, l| 
  memo << [memo.last, l].compact.join('_') 
end.reverse
########################################################
([items]*items.size).map.with_index(&:take).map do |e| 
  e.join('_')
end.reject(&:empty?).reverse

My fave: 我最喜欢的:

([str]*str.count('_')).map.with_index do |s, i| 
  s[/\A([^_]+_){#{i + 1}}/][0...-1]
end.reverse

Ruby ships with a module for abbreviation . Ruby附带了一个缩写模块。

require "abbrev"

puts ["a_b_c_d_e".tr("_","")].abbrev.keys[1..-1].map{|a| a.chars*"_"}
# => ["a_b_c_d", "a_b_c", "a_b", "a"]

It works on an Array with words - just one in this case. 它适用于带有单词的数组-在这种情况下只有一个。 Most work is removing and re-placing the underscores. 大多数工作是删除并重新放置下划线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM