开发者

Ruby: How to strip a string and get the removed whitespaces?

Given a string, I would like to strip it, but I want to have the pre and post removed whitespaces. For example:

my_strip("   hello world ")   # => ["   ", "hello world", " "]
my_strip("hello world\t ")    # => ["", "hello world", "\t "]
my_strip("hello world")       # => ["", "hello world", "开发者_运维知识库"]

How would you implement my_strip ?


Solution

def my_strip(str)
  str.match /\A(\s*)(.*?)(\s*)\z/m
  return $1, $2, $3
end

Test Suite (RSpec)

describe 'my_strip' do
  specify { my_strip("   hello world ").should      == ["   ", "hello world", " "]     }
  specify { my_strip("hello world\t ").should       == ["", "hello world", "\t "]      }
  specify { my_strip("hello world").should          == ["", "hello world", ""]         }
  specify { my_strip(" hello\n world\n \n").should  == [" ", "hello\n world", "\n \n"] }
  specify { my_strip(" ... ").should                == [" ", "...", " "]               }
  specify { my_strip(" ").should                    == [" ", "", ""]                   }
end


Well, this is a solution that I come up with:

def my_strip(s)
  s.match(/\A(\s*)(.*?)(\s*)\z/)[1..3]
end

But, I wonder if there are other (maybe more efficient) solutions.


def my_strip( s )
  a = s.split /\b/
  a.unshift( '' ) if a[0][/\S/]
  a.push( '' ) if a[-1][/\S/]
  [a[0], a[1..-2].join, a[-1]]
end


def my_strip(str)
  sstr = str.strip
  [str.rstrip.sub(sstr, ''), sstr, str.lstrip.sub(sstr, '')]
end


I would use regexp:

def my_strip(s)
    s =~ /(\s*)(.*?)(\s*)\z/
    *a = $1, $2, $3
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜