1

as the title says, i'm trying to write a function to remove spaces. This is where i am so far, but it seems i'm missing something.

def remove(x)
  if x.include? " "
    x.gsub!(/ /,"")
  end
end
5
  • Well, for some reason if the space is at the end of the string, it does not remove it. Commented Dec 21, 2018 at 14:47
  • I'm just trying to learn the language at the moment, but it seems in codewars it won't work. "It should work for random inputs too, test for 1q - Expected: "1q", instead got: nil " Commented Dec 21, 2018 at 14:54
  • 1
    Remove the if and use not banged version. The banged version mutates the variable and return nil if no substitution was made. x.delete(' ') will do. Commented Dec 21, 2018 at 14:58
  • 1
    Possible duplicate of Ruby function to remove all white spaces? Commented Dec 21, 2018 at 17:03
  • If you browse the instance methods of the class String, you will find three methods that fit the bill: gsub, tr and delete. Which is best here? Commented Dec 21, 2018 at 17:40

2 Answers 2

3

I think you're probably checking the output of the function, right?

You have something like

remove('1q')
=> nil

This is because the remove method isn't returning anything if there's no space found. Just make sure you return the modified value.

def remove(x)
  if x.include? " "
    x.gsub!(/ /,"")
  end
  x  # this is the last executed command and so will be the return value of the method
end

And now you'll see

 remove('1q')
=> "1q"

Note that your method actually mutates the object, so you don't really need to test what's returned, you can just inspect the variable with the original value. Do...

test_value = 'My carrot'
remove(test_value)

p test_value
=> "Mycarrot"

Finally, as has been pointed out, you don't need to surround it in an if clause, the gsub! will work only on any spaces it finds and will otherwise do nothing.

def remove(x)
  x.gsub!(' ', '')
  x
end

Note that you still need to return the x variable as if gsub! does nothing, it returns nil

The method gsub (on the other hand) doesn't mutate, it will always return a new value which will be the string with any substitutions made, so you could do

def remove(x)
  x.gsub(' ','')
end

And this will always return a value regardless of whether substitution occured... but the original object will be unchanged. (The returned value will have a different object_id)

Sign up to request clarification or add additional context in comments.

Comments

1

more simple, you can do:

def remove_blank_spaces(str)
  str.delete(' ')
end

Other option:

def remove_blank_spaces(str)
  str.gsub(' ', '')
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.