Ruby Remove string Whitespace instance

Source: Internet
Author: User


Use the String#strip method to remove all spaces


The code is as follows

"Hello". Strip #=> "Hello"
"Tgoodbyern". Strip #=> "Goodbye"


In addition, Lstrip and Rstrip remove the spaces at the left and right ends of the string, respectively


The code is as follows

"Hello". Lstrip #=> "Hello"
"Hello". Lstrip #=> "Hello"
"Hello". Rstrip #=> "Hello"
"Hello". Rstrip #=> "Hello"


The above method is to return the string copy, such as to change the original string object, using string#strip!, string#lstrip!, string#rstrip!. Returns nil if the object does not change


The code is as follows

"Hello". rstrip! #=> Nil



The code implementation inserts a space for each of the two characters of a string, and finally returns a result string. It is also best to provide an inverse procedure for this string conversion process together.


  code is as follows

str = ' ABCD '

Str =~ s/(? <=w{2}) (? =w{2}/""/

str = "AB CD"

puts Str.split.join ("). to_s

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.