简体   繁体   中英

Ruby - How to remove only 1 whitespace from string

I try to remove 1 whitespace from this string:

m y  r e a l  n a m e  i s  d o n a l d  d u c k

Expected result:

my real name is donald duck

My code are:

def solve_cipher(input)

  input.split('').map { |c| (c.ord - 3).chr }.join(' ') # <- Here I tried everything

end

puts solve_cipher('p| uhdo qdph lv grqdog gxfn') 
# => m y  r e a l  n a m e  i s  d o n a l d  d u c k

I tried everything to solve my problem, example:

input.....join(' ').squeeze(" ").strip # => m y  r e a l  n a m e...

or

input.....join.gsub(' ','') # => myrealnameisdonaldduck

or

input.....join(' ').lstrip # => m y  r e a l  n a m e...

and so on...

Well, you could split the string into words first, then split each word into characters. Using the same method you used in your code, it could look like this.

def solve_cipher(input) input.split(' ').map{ |w| w.split('').map { |c| (c.ord - 3).chr}.join('')}.join(' ') end

When joining the characters in the same word, we put no space between them; when joining the words together we put one space between them.

As stated in the question, you are using Rails, so you can also try squish method:

def solve_cipher( input )
  input.split('  ').map(&:squish).join(' ')
end
str = "m y  r e a l  n a m e  i s  d o n a l d  d u c k"

str.gsub(/\s(?!\s)/,'')
  #=> "my real name is donald duck"

The regex matches a whitespace character not followed by another whitespace character and replaces the matched characters with empty strings. (?!\\s) is a negative lookahead that matches a whitespace.

If more than two spaces may be present between words, first replace three or more spaces with two spaces, as follows.

str = "m y     r e a l      n a m e  i s  d o n a l d  d u c k"

str.gsub(/\s{3,}/, "  ").gsub(/\s(?!\s)/,'')
  #=> "my real name is donald duck"

I know that it is not a fancy way of doing it but you could just try to create a new string and have a function traversal(input) with a counter initiated at 0, that would return this new string.

It would go through your input (which is here your string) and if the counter is 0 and it sees a space it just ignores it, increments a counter and go to the next character of the string.

If the counter is different of 0 and it sees a space it just concatenates it to the new string.

And if the counter is different of 0 and it sees something different of a space, it concatenates it to the new string and counter equals 0 again.

The trick is to use a capture group

"myrealnameisdonaldduc k".gsub(/(\\s)(.)/, '\\2')

=> "my real name is donald duck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM