Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces around hyphen in Ruby

Tags:

string

regex

ruby

I have the next strings:

'foo-bar'

'foo - bar'

'foo -bar'

'foo- bar'

'foo- bar-baz'

'foo - bar -baz'

'foo- bar baz'

etc.

What is the best way in ruby to make them all without spaces around hyphens? Spaces between words without hyphens should stay.

Example of expected result: 'foo-bar' 'foo-bar-baz' 'foo-bar baz'

like image 414
ruby_dev Avatar asked Mar 14 '26 02:03

ruby_dev


2 Answers

The quick and effective way is with a regular expression:

"foo-bar -baz - blerp blorp".gsub(/\s*-\s*/, "-")
=> "foo-bar-baz-blerp blorp"

The \s* means "zero or more whitespace characters". Note that this will match tabs as well as spaces. If you only want to match spaces, use [ ]* instead.

like image 194
mroach Avatar answered Mar 15 '26 15:03

mroach


Use regular expressions. I believe you regular expression should eq to something like this:

regex = /\s*-\s*/

test_strings = ["foo-bar baz", "foo - bar baz", "foo -bar"]

test_strings.map do |test_string|
  test_string.gsub(regex, "-")
end
# => ["foo-bar baz", "foo-bar baz", "foo-bar"]

A bonus tip, here is a great app to construct your regular expressions: https://rubular.com/

like image 45
Michael Kosyk Avatar answered Mar 15 '26 16:03

Michael Kosyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!