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
:
var_name.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
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
)
Ruby: Remove whitespace chars at the beginning of a string
String#lstrip
(or String#lstrip!
) is what you're after.
desired_output = example_array.map(&:lstrip)
More comments about your code:
delete_if {|x| x == ""}
can be replaced withdelete_if(&:empty?)
- Except you want
reject!
becausedelete_if
will only return a different array, rather than modify the existing one. words.each {|e| e.lstrip!}
can be replaced withwords.each(&:lstrip!)
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 machinesplit(",")
can be replaced withsplit(", ")
orsplit(/, */)
(or/, ?/
if there should be at most one space)
So now it looks like:
words = params[:word].gsub("\n", ",").split(/, ?/)
words.reject!(&:empty?)
words.each(&:lstrip!)
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?)
end
temp_array.flatten(1)
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
Why Is the Shovel Operator (≪≪) Preferred Over Plus-Equals (+=) When Building a String in Ruby
Why Is This Rmagick Call Generating a Segmentation Fault
What Does the Question Mark At the End of a Method Name Mean in Ruby
Find_Spec_For_Exe': Can't Find Gem Bundler (≫= 0.A) (Gem::Gemnotfoundexception)
Best Way to Require All Files from a Directory in Ruby
Ruby: What Does 'Require: False' in Gemfile Mean
Rails :Dependent =≫ :Destroy VS :Dependent =≫ :Delete_All
How to Search File Text For a Pattern and Replace It With a Given Value
Why Doesn't Ruby Support Method Overloading
Backslashes in Single Quoted Strings Vs. Double Quoted Strings
Cannot Install Json Gem in Rails Using Windows
Error: Failed to Build Gem Native Extension on Mavericks
Printing the Source Code of a Ruby Block
Ruby Style: How to Check Whether a Nested Hash Element Exists
Pg::Error: Select Distinct, Order by Expressions Must Appear in Select List