user3267020
user3267020

Reputation: 65

Trying to remove spaces from a string RUBY

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

Upvotes: 1

Views: 3354

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36880

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)

Upvotes: 3

Dimitrius Lachi
Dimitrius Lachi

Reputation: 1287

more simple, you can do:

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

Other option:

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

Upvotes: 1

Related Questions