aldanux aldanux - 6 months ago 8
Ruby Question

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...

Answer

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.