tags:

views:

147

answers:

3

The title is my question, thank you in advance for your answer!

+7  A: 

The simplest version:

"this is an example".tr(" ", "-")
#=> "this-is-an-example"

You could also do something like this, which is slightly more robust and easier to extend by updating the regular expression:

"this is an example".gsub(/\s+/, "-")
#=> "this-is-an-example"

The above will replace all chunks of white space (any combination of multiple spaces, tabs, newlines) to a single dash.

See the String class reference for more details about the methods that can be used to manipulate strings in Ruby.

If you are trying to generate a string that can be used in a URL, you should also consider stripping other non-alphanumeric characters (especially the ones that have special meaning in URLs), or replacing them with an alphanumeric equivalent (example, as suggested by Rob Cameron in his answer).

molf
+4  A: 

If you are trying to make something that is a good URL slug, there are lots of ways to do it.

Generally, you want to remove everything that is not a letter or number, and then replace all whitespace characters with dashes.

So:

s = "this is an 'example'"
s = s.gsub(/\W+/, ' ').strip
s = s.gsub(/\s+/,'-')

At the end s will equal "this-is-an-example"

I used the source code from a ruby testing library called contest to get this particular way to do it.

Benjamin
+1  A: 

If you're using Rails take a look at parameterize(), it does exactly what you're looking for:

http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367

foo = "Hello, world!"
foo.parameterize => 'hello-world'
Rob Cameron
cheers mate, that is exactly what I want to, but it seems not working with Unicode and it turns out "parameterize" method not found here
helloedwin