Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 454 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Ruby function to remove all white spaces?

#11
My personal preference is using the method `.tr`

as in:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"


Thanks to @FrankScmitt for pointing out that to make this delete _all_ whitespace(not just spaces) you would need to write it as such:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"
Reply

#12
Ruby's `.scan()` and `.join()` methods of String can also help to overcome whitespace in string.

`scan(/\w+/).join` will remove all spaces and join the string

string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"

It is also removing space from left and right part of the string. Means `ltrim`, `rtrim` and `trim`. Just in case if someone has background over `C`, `FoxPro` or `Visual Basic` and jump in `Ruby`.

`
2.1.6 :002 > string = " White spaces in me ".scan(/\w+/).join
=> "Whitespacesinme"
2.1.6 :003 > string = " White spaces in me".scan(/\w+/).join
=> "Whitespacesinme"
2.1.6 :004 > string = "White spaces in me ".scan(/\w+/).join
=> "Whitespacesinme"
2.1.6 :005 >
`
Reply

#13
For behavior exactly matching PHP `trim`, the simplest method is to use the `String#strip` method, like so:

string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
new_string = string.strip
puts "Updated [#{new_string}]:#{new_string.length}"

Ruby also has an edit-in-place version, as well, called `String.strip!` (note the trailing '!'). This doesn't require creating a copy of the string, and can be significantly faster for some uses:

string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
string.strip!
puts "Updated [#{string}]:#{string.length}"

Both versions produce this output:

Original [ Many have tried; many have failed! ]:40
Updated [Many have tried; many have failed!]:34

I created a benchmark to test the performance of some basic uses of `strip` and `strip!`, as well as some alternatives. The test is this:

require 'benchmark'

string = 'asdfghjkl'
Times = 25_000

a = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
b = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
c = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
d = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }

puts RUBY_DESCRIPTION
puts "============================================================"
puts "Running tests for trimming strings"

Benchmark.bm(20) do |x|
x.report("s.strip:") { a.each {|s| s = s.strip } }
x.report("s.rstrip.lstrip:") { a.each {|s| s = s.rstrip.lstrip } }
x.report("s.gsub:") { a.each {|s| s = s.gsub(/^\s+|\s+$/, "") } }
x.report("s.sub.sub:") { a.each {|s| s = s.sub(/^\s+/, "").sub(/\s+$/, "") } }

x.report("s.strip!") { a.each {|s| s.strip! } }
x.report("s.rstrip!.lstrip!:") { b.each {|s| s.rstrip! ; s.lstrip! } }
x.report("s.gsub!:") { c.each {|s| s.gsub!(/^\s+|\s+$/, "") } }
x.report("s.sub!.sub!:") { d.each {|s| s.sub!(/^\s+/, "") ; s.sub!(/\s+$/, "") } }
end

These are the results:

ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14]
============================================================
Running tests for trimming strings
user system total real
s.strip: 2.690000 0.320000 3.010000 ( 4.048079)
s.rstrip.lstrip: 2.790000 0.060000 2.850000 ( 3.110281)
s.gsub: 13.060000 5.800000 18.860000 ( 19.264533)
s.sub.sub: 9.880000 4.910000 14.790000 ( 14.945006)
s.strip! 2.750000 0.080000 2.830000 ( 2.960402)
s.rstrip!.lstrip!: 2.670000 0.320000 2.990000 ( 3.221094)
s.gsub!: 13.410000 6.490000 19.900000 ( 20.392547)
s.sub!.sub!: 10.260000 5.680000 15.940000 ( 16.411131)

Reply

#14
I was trying to do this as I wanted to use a records "title" as an id in the view but the titles had spaces.

a solution is:

record.value.delete(' ') # Foo Bar -> FooBar


Reply

#15
You can try this:

"ab c d efg hi ".split.map(&:strip)

in order to get this:

["ab, "c", "d", "efg", "hi"]


or if you want a single string, just use:

"ab c d efg hi ".split.join

Reply

#16
[`String#strip`](

[To see links please register here]

) - remove all whitespace from the start and the end.

[`String#lstrip`](

[To see links please register here]

) - just from the start.

[`String#rstrip`](

[To see links please register here]

) - just from the end.

[`String#chomp`](

[To see links please register here]

) (with no arguments) - deletes line separators (`\n` or `\r\n`) from the end.

[`String#chop`](

[To see links please register here]

) - deletes the last character.

[`String#delete`](

[To see links please register here]

) - `x.delete(" \t\r\n")` - deletes all listed whitespace.

[`String#gsub`](

[To see links please register here]

) - `x.gsub(/[[:space:]]/, '')` - removes all whitespace, including [unicode ones](

[To see links please register here]

).

---
**Note**: All the methods above return a new string instead of mutating the original. If you want to change the string in place, call the corresponding method with `!` at the end.
Reply

#17
Use gsub or delete. The difference is gsub could remove tabs, while delete cannot. Sometimes you do have tabs in files which are added by the editors.

a = "\tI have some whitespaces.\t"
a.gsub!(/\s/, '') #=> "Ihavesomewhitespaces."
a.gsub!(/ /, '') #=> "\tIhavesomewhitespaces.\t"
a.delete!(" ") #=> "\tIhavesomewhitespaces.\t"
a.delete!("/\s/") #=> "\tIhavesomewhitespaces.\t"
a.delete!('/\s/') #=> using single quote is unexpected, and you'll get "\tI have ome whitepace.\t"

Reply

#18
The gsub method will do just fine.
The gsub method can be called on a string and says:


a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring

The gsub method searches for every occurrence of the first argument
and replaces it with the second argument. In this case, it will replace every space within the string and remove it.

Another example:

b = "the white fox has a torn tail"
Let's replace every occurrence of the letter " t " with a capital " T "

b = b.gsub("t","T")
puts b
#Output: The whiTe fox has a Torn Tail
Reply

#19
**If you are using Rails/ActiveSupport**, you can use `squish` method. It removes white space on both ends of the string and groups multiple white space to single space.

For eg.

" a b c ".squish

will result to:

"a b c"

Check [this reference from api.rubyonrails.org](

[To see links please register here]

).
Reply

#20
I'm a bit late to the game, but I remove trailing and leading whitespaces by using `strip!`. If you have an array, such as I did, I needed to iterate through the array and save it after the instance ended. The ! took care of this. This removed all whitespaces at the end or the beginning, not just the first leading or the last trailing.

For example:

array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end
This would output to: ["hello","Melanie", "is", "new ", "to", "programming"]. I further explored/shared this [in a video I made to highlight this code for similar question I had][1].

I'm newer to programming and using strip did not work as it didn't save it to the array after the loop ended.


[1]:
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through