ToddT ToddT - 1 month ago 13
Ruby Question

More efficient way than gsub twice

I have an array of strings:

orders = ["#1174.2", "#1176.3", "#1177.2", "#1178.1", "#1180.1"]


I am doing this to remove the leading "#" and trailing ".1"

orders.each do |numbers|
puts numbers.gsub!("#", "").gsub!(/\.[0-9]/, "")
end
# returns 1174, 1176 etc..


The trailing ".1" could be any number to 9.. is there a better/faster way to do this?

Answer
cleaned_orders = orders.map { |numbers| numbers.gsub(/(^#|\.\d$)/, '') }

cleaned_orders now contains: ['1174', '1176', '1177', '1178', '1180']

(^#|\.\d$) matches # if it is at the beginning of the string or a single period followed by a single digit at the end of the string.

Comments