Tuesday, May 18, 2010

Ruby: String Manipulators

So I'm working on a feature that requires the input of a text field to be formatted in uppercase and have all spaces and dashes removed from the string.

So in the RAILS console, try:

>> a="Abs-a23-pdk 23 aB1"
=>"Abs-a23-pdk 23 aB1"
>> a.gsub!(" ", "")
=>"Abs-a23-pdk23aB1"
>> a.gsub!("-", "")
=> "Absa23pdk23aB1"
>> a.upcase!
=> "ABSA23PDK23AB1"
>> a
=> "ABSA23PDK23AB1"

Notes:
You need the "!" after the command to modify (make changes permanent) the receiver.

If you want to be fancy and write one line to do the 3 methods, try:
>> a="Abs-a23-pdk 23 aB1"
=> "Abs-a23-pdk 23 aB1"
>> a.gsub!(/[ -]/, "").upcase!
=> "ABSA23PDK23AB1"
>> a
=> "ABSA23PDK23AB1"

Notes:
So pretty much everything in between the brackets is removed is removed
[%$ _-] in this case, %, $, _, - and spaces are removed.
[1-9] in this case, all numbers are removed.

Here a link to the official documentation:
http://ruby-doc.org/core/classes/String.html

Another Link:
http://www.techotopia.com/index.php/Ruby_String_Replacement,_Substitution_and_Insertion

No comments:

Post a Comment