我有一个这样的数组:
inList = ["edge_rabbit", "nsp_edge_rabbit", "services", "syslog", "master_rabbit", "mongod", ...]
如何使用以_rabbit
结尾的元素或格式为mongo[cds]
的元素,并生成逗号分隔的字符串,如下所示?
"edge_rabbit, nsp_edge_rabbit, master_rabbit"
答案 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"
如果除了mongo
,c
或d
之外,s
可能包含其他跟踪字符的变体,请使用:
in_list.grep(/(?:^mongo[cds])|(?:_rabbit$)/).join(', ') # => "edge_rabbit, nsp_edge_rabbit, master_rabbit, mongod"