Ruby Function to Remove All White Spaces

Removing all whitespace from a string in Ruby

You can use something like:

var_name.gsub!(/\s+/, '')

Or, if you want to return the changed string, instead of modifying the variable,

var_name.gsub(/\s+/, '')

This will also let you chain it with other methods (i.e. something_else = var_name.gsub(...).to_i to strip the whitespace then convert it to an integer). gsub! will edit it in place, so you'd have to write var_name.gsub!(...); something_else = var_name.to_i. Strictly speaking, as long as there is at least one change made,gsub! will return the new version (i.e. the same thing gsub would return), but on the chance that you're getting a string with no whitespace, it'll return nil and things will break. Because of that, I'd prefer gsub if you're chaining methods.

gsub works by replacing any matches of the first argument with the contents second argument. In this case, it matches any sequence of consecutive whitespace characters (or just a single one) with the regex /\s+/, then replaces those with an empty string. There's also a block form if you want to do some processing on the matched part, rather than just replacing directly; see String#gsub for more information about that.

The Ruby docs for the class Regexp are a good starting point to learn more about regular expressions -- I've found that they're useful in a wide variety of situations where a couple of milliseconds here or there don't count and you don't need to match things that can be nested arbitrarily deeply.

As Gene suggested in his comment, you could also use tr:" \t\r\n", '')

It works in a similar way, but instead of replacing a regex, it replaces every instance of the nth character of the first argument in the string it's called on with the nth character of the second parameter, or if there isn't, with nothing. See String#tr for more information.

Trying to remove spaces from a string RUBY

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

You have something like

=> 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!(/ /,"")
x # this is the last executed command and so will be the return value of the method

And now you'll see

=> "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'

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!(' ', '')

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(' ','')

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)

Ruby: Remove whitespace chars at the beginning of a string

String#lstrip (or String#lstrip!) is what you're after.

desired_output =

More comments about your code:

  1. delete_if {|x| x == ""} can be replaced with delete_if(&:empty?)
  2. Except you want reject! because delete_if will only return a different array, rather than modify the existing one.
  3. words.each {|e| e.lstrip!} can be replaced with words.each(&:lstrip!)
  4. delete("\r") should be redundant if you're reading a windows-style text document on a Windows machine, or a Unix-style document on a Unix machine
  5. split(",") can be replaced with split(", ") or split(/, */) (or /, ?/ if there should be at most one space)

So now it looks like:

words = params[:word].gsub("\n", ",").split(/, ?/)

I'd be able to give more advice if you had the sample text available.

Edit: Ok, here goes:

temp_array = text.split("\n").map do |line|
fields = line.split(/, */)
non_empty_fields = fields.reject(&:empty?)

The methods used are String#split, Enumerable#map, Enumerable#reject and Array#flatten.

Ruby also has libraries for parsing comma seperated files, but I think they're a little different between 1.8 and 1.9.

Remove all space characters from string in Rails

Use the destructive delete method. #delete!

number.delete!(' ').gsub(/\D/)

Delete all the whitespaces that occur after a word in ruby

There are numerous ways this could be accomplished without without a regular expressions, but using them could be the "cleanest" looking approach without taking sub-strings, etc. The regular expression I believe you are looking for is /(?!^)(\s)/.

"  hello world! How is it going?".gsub(/(?!^)(\s)/, '')
#=> " helloworld!Howisitgoing?"

The \s matched any whitespace character (including tabs, etc), and the ^ is an "anchor" meaning the beginning of the string. The ! indicates to reject a match with following criteria. Using those together to your goal can be accomplished.

If you are not familiar with gsub, it is very similar to replace, but takes a regular expression. It additionally has a gsub! counter-part to mutate the string in place without creating a new altered copy.

Note that strictly speaking, this isn't all whitespace "after a word" to quote the exact question, but I gathered from your examples that your intentions were "all whitespace except beginning of string", which this will do.

How can I remove all blank-spaces?

See the documentation on String#replace for why it doesn't work as expected (this is an unfortunate function with a confusing name resulting from the fact that Ruby strings are mutable):

Replaces the [entire] contents [of the String] and taintedness of str with the corresponding values in other_str.

You probably want String#strip which behaves like "TRIM" in other contexts:

Returns a copy of str with leading and trailing whitespace removed.

" Hello world! ".strip  # => "Hello world!"

(If you wish to remove spaces everywhere, see String#gsub - I'll let you look that one up.)

Related Topics

Leave a reply