0

I have an array like this:

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

How can I take the elements that end with _rabbit or elements with the format mongo[cds], and generate a comma separated string like the following?

"edge_rabbit, nsp_edge_rabbit, master_rabbit"

2 Answers 2

2

Is this the one you are looking for using String#end_with? and 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"

or

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"
Sign up to request clarification or add additional context in comments.

3 Comments

I knew this gonna be so simple that I'm not even thinking about it. Thanks a lot for the prompt answer. Cheers!!
On a separate note, is it possible to use pattern-matching/regex with include, like inList.include? ()? e.g. to check if any of the array elements ends with _rabbit. Cheers!!
@MacUsers not with #include? But with yes #grep you can do. See my update.
1

I'd use some small patterns:

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"

Or:

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

If it's possible to have variations on mongo with other trailing characters besides c, d or s, then use:

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

1 Comment

@the Tin Man: Very useful for a Ruby newbie; thanks for heads up! Cheers!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.