我有以下内容:
input string = "1234"
output new_array should = [12, 3, 4, 34]
答案 0 :(得分:2)
def string_to_array(string)
noun = ["d", "fgh", "i", "jk", "bcd", "cdef"]
verb = ["cd", "ef", "f", "jkl", "abc"]
ary = (noun+verb).select { |s| string.include? s }
ary.unshift(ary.delete(string)).compact
end
string = "cdef"
string_to_array(string) #=> ["cdef", "d", "cd", "ef", "f"]
我使用了Array#select
,Array#+
,Array#delete
,Array#unshift
,Array#compact
和String#include?
。
如果要从输出数组中删除重复项,请使用Array#uniq
答案 1 :(得分:0)
您可以将String#scan(尤其是文档的最后一句话)与正则表达式一起使用。我的目的是演示这种方法,而不是建议它是首选方法。
nouns = ["cdef", "d", "fgh", "i", "jk", "bcd"]
verbs = ["cd", "ef", "f", "jkl", "abc"]
R = Regexp.new (nouns+verbs).map { |s| "(?=(#{s}))?" }.join
#=> /(?=(cdef))?(?=(d))?(?=(fgh))?(?=(i))?(?=(jk))?(?=(bcd))?(?=(cd))?(?=(ef))?(?=(f))?(?=(jkl))?(?=(abc))?/
def string_to_array(str, nouns, strings)
str.scan(R).flatten.compact
end
str = "cdef"
string_to_array(str, nouns, verbs)
#=> ["cdef", "cd", "d", "ef", "f"]
注意:
str.scan(R)
#=> [["cdef", nil, nil, nil, nil, nil, "cd", nil, nil, nil, nil],
# [nil, "d", nil, nil, nil, nil, nil, nil, nil, nil, nil],
# [nil, nil, nil, nil, nil, nil, nil, "ef", nil, nil, nil],
# [nil, nil, nil, nil, nil, nil, nil, nil, "f", nil, nil],
# [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]]
(?=(cdef))?
((?=(cdef)?)
也有效)是捕获组中的正向超前。它要求字符串中的特定位置后跟先行内容,但不属于匹配项本身。问号使前瞻性成为可选。