Remove leading and trailing spaces

Is there a way to remove ALL leading the trailing spaces in a string
please?

For example,
’ hello’ => ‘hello’
’ hello ’ => ‘hello’
’ hello ’ => ‘hello’

Thanks in advance

Grace

Take a look here: http://www.ruby-doc.org/core/

More specifically:
http://www.ruby-doc.org/core/classes/String.html#M000842

It’s strip method

Thanks Luis

Try strip or strip!
Good luck,

-Conrad

strip returns its result, strip! modifies it’s caller directly

Grace X. wrote:

Grace


Sincerely,

William P.

http://www.billpratt.net
[email protected]

Try strip or strip!

Apart from the return variable can be a nil object for strip! Is there
any other difference between the two at all?

What would be the senario that you’d use strip! please?

Thanks

Grace

What would be the senario that you’d use strip! please?

Depends what effect you want to see: the ! version operates on the
String object itself, the other returns a new String as the result of
the strip operation:

s = ’ xyz ’

s2 = s.strip
s => ’ xyz ’ # s is unchanged
s2 => ‘xyz’

s.strip!
s => ‘xyz’ # s changes

Mike wrote:

s = ’ xyz ’

s2 = s.strip
s => ’ xyz ’ # s is unchanged
s2 => ‘xyz’

s.strip!
s => ‘xyz’ # s changes

If my s = ‘xyz’ in the first place, would s.srip! cause any problem, as
the documentation seems to suggest that s.strip! in this case will
return NIL?

Thanks

Grace

Grace X. wrote:

s.strip!
s => ‘xyz’ # s changes

If my s = ‘xyz’ in the first place, would s.srip! cause any problem, as
the documentation seems to suggest that s.strip! in this case will
return NIL?

Hi Grace,

You are right!

s.strip! will return nil. So, if you do
t = s.strip! then t will be nil as you pointed out. s will still be
valid.

Cheers,
Mohit.
8/22/2007 | 11:42 AM.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs