基于模式匹配从数组生成包含元素的字符串

时间:2013-09-10 20:30:52

标签: ruby arrays pattern-matching

我有一个这样的数组:

inList = ["edge_rabbit", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod", ...]

如何使用以_rabbit结尾的元素或格式为mongo[cds]的元素,并生成逗号分隔的字符串,如下所示?

"edge_rabbit, nsp_edge_rabbit, master_rabbit"

2 个答案:

答案 0 :(得分:2)

这是您正在寻找的使用String#end_with?Array#select吗?

inList = ["edge_rabbit", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod"]
inList.select{|e| e.end_with?('_rabbit')}.join(", ")
# => "edge_rabbit, nsp_edge_rabbit, master_rabbit"

inList = ["edge_rabbit", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod"]
inList.grep(/_rabbit$/).join(", ")
# => "edge_rabbit, nsp_edge_rabbit, master_rabbit"


inList = ["edge_rabbit","_rabbit_ut", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod","mongos","mongoy"]
inList.grep(/_rabbit$|^mongo[cds]/).join(", ")
# => "edge_rabbit, nsp_edge_rabbit, master_rabbit, mongod, mongos"

答案 1 :(得分:1)

我会使用一些小图案:

in_list = ["edge_rabbit", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod"]

in_list.select{ |s| s[/(?:^mongo)|(?:_rabbit$)/] }.join(', ') # => "edge_rabbit, nsp_edge_rabbit, master_rabbit, mongod"

或者:

in_list.grep(/(?:^mongo)|(?:_rabbit$)/).join(', ') # => "edge_rabbit, nsp_edge_rabbit, master_rabbit, mongod"

如果除了mongocd之外,s可能包含其他跟踪字符的变体,请使用:

in_list.grep(/(?:^mongo[cds])|(?:_rabbit$)/).join(', ') # => "edge_rabbit, nsp_edge_rabbit, master_rabbit, mongod"