-2

My goal is to replace spaces and "/" with '-' from the input:

name = "chard / pinot noir"

to get:

"chard-pinot-noir"

My first attempt is:

name.gsub(/ \/\ /, '-') #=> "chart-pinot noir"

My second attempt is:

name.gsub(/\/\s+/, '-') #=> "chard -pinot noir"

My third attempt is:

name.gsub(/\s+/, '-') #=> "chard-/-pinot-noir"

This article helped. The first group checks for a forward slash /, and contains a break. The second portion replaces a forward slash with '-'. However, the space remains. I believe /s matches spaces, but I can't get it to work while simultaneously checking for forward slash.

My question is how can I get the desired result, shown above, with varying strings using either regex or a ruby helpers. Is there a preferred way? Pro / Con ?

thesayhey
  • 858
  • 2
  • 15
  • 36

1 Answers1

1

If you don't know much about regex, you can do this way.

name = "chard / pinot noir"
(name.split() - ["/"]).join("-")
=> "chard-pinot-noir"

I think the best way is use with regex as @Sagar Pandya described above.

name.gsub(/[\/\s]+/,'-')
=> "chard-pinot-noir"
TheVinspro
  • 301
  • 3
  • 15