Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby append string to each element in an array

I am working on analytics ruby api client. When making a call i am sending the params as

dimensions = ["ga:hostName", "pagePath"]
metrics = ["pageValue", "ga:pageviews"]
.call_analytics(dimensions, metrics)

Even if the user does not enter "ga:" when passing params, the code should append "ga:" in the params.

I have done it this way.

dimensions = dimensions.map{|a| ("ga:" + a.split(":").last).split}.flatten
metrics = metrics.map{|a| ("ga:" + a.split(":").last).split}.flatten

Is there a better way to do it?

like image 371
Kumar Avatar asked Oct 27 '25 09:10

Kumar


1 Answers

["ga:hostName", "pagePath"]
.map{|s| s.sub(/\A(?!ga:)/, "ga:")}
#=> ["ga:hostName", "ga:pagePath"]

["pageValue", "ga:pageviews"]
.map{|s| s.sub(/\A(?!ga:)/, "ga:")}
#=> ["ga:pageValue", "ga:pageviews"]

or

["ga:hostName", "pagePath"]
.map{|s| s.start_with?("ga:") ? s : s.prepend("ga:")}
#=> ["ga:hostName", "ga:pagePath"]

["pageValue", "ga:pageviews"]
.map{|s| s.start_with?("ga:") ? s : s.prepend("ga:")}
#=> ["ga:pageValue", "ga:pageviews"]
like image 63
sawa Avatar answered Oct 28 '25 23:10

sawa