Stef Hej Stef Hej - 6 months ago 12
Ruby Question

Ruby transform string of range measurements into a list of the measurements?

I have a sample string that I would like to transform, from this:

#21inch-#25inch


to this:

#21inch #22inch #23inch #24inch #25inch


Using Ruby, please show me how this can be done.

Answer

You can scan your string and working with range of strings:

numbers = "#21inch-#25inch".scan(/\d+/)
=> ["21", "25"]
Range.new(*numbers).map{ |s| "##{s}inch" }.join(" ")
=> "#21inch #22inch #23inch #24inch #25inch"

This solution working only if your string has a format like in your instance. For other cases you should write your own specific solution.

Comments