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'
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With