Reputation: 26008
What I have
"path1/path2/path3"
what I want
"my_namespace:path1/my_namespace:path2/my_namespace:path3"
and I did:
a = "path1/path2/path3"
b = a.split("/").map{ |item| "my_namespace:"+ item}
puts b.join("/")
Of course, it works. But I'm curious if there is any other better way to do that.
Upvotes: 1
Views: 53
Reputation: 1378
Seems like a good use case for String#gsub
:
a = "path1/path2/path3".gsub(%r{[^/]+/?}) { |m| "mynamespace:#{m}" }
p a #=> "mynamespace:path1/mynamespace:path2/mynamespace:path3"
Upvotes: 1
Reputation: 168071
a.gsub(/(?<=^|\/)/, "my_namespace:")
# => "my_namespace:path1/my_namespace:path2/my_namespace:path3"
Upvotes: 2
Reputation: 21791
Maybe you meant different namespaces for your paths. If so then you can use zip
"path1/path2/path3".split('/').zip(['namespace1','namespace2','namespace3']).
map { |p,n| n + ':' + p }.join('/')
=> "namespace1:path1/namespace2:path2/namespace3:path3"
Upvotes: 0