Getting Familiar With the Common Methods of the String Class
|
In this short tutorial we'll examine the use of the more
common string methods in Ruby.
|
by Itay Moav
This tutorial is intended for programmers experienced with
object oriented programming and basic knowledge on how to define strings in Ruby.
This article covers the following:
- The logic behind the naming of methods in Ruby
- What is Chaining
- Some of the common String methods
The class method [new]
I call the [new] a class method since you can't activate the
method [new] on an instance of a String. All the following
will produce is an error:
a='kkk'.new
a='hhh'
a.new
a='hhh'
b=a.new
A class method can be activated using only the class:
a=String.new 'kkk'
puts a
In this example I have instantiated a new string object,
which is referenced by the variable [a]. [new] is a class
method which returns an instance of this class (i.e. an
object).
The Postfixes of Methods: none,[!],[?]
In Ruby you will see some methods which their names are only
alpha-numeric, like [chomp],[chop],[split]. You will see
method names ending with the exclamation mark, like
[chop!],[tr_s!], And you will see methods ending with the
question mark, like end_with?,mbchar?
A method that ends with no [!] or no [?] means it
returns a new object with the modified value. The original
object stays the same. I will use the instance method
[chop] to demonstrate. [chop] creates a new string with the
same value as the original string, removing the last
character:
a='1234'
b=a.chop
puts "I am a:#{a} and I am b:#{b}"
This will print the following:
I am a:1234 and I am b:123
A method that ends with a [?] means it returns a boolean
value. I will use the instance method [end_with?] to
demonstrate. This method is used to check if the string ends
with the string I send as input. Notice it returns [true] or
[false] only:
puts 'hola'.end_with?('la')
#prints [true]
puts 'hola'.end_with?('ho')
#prints [false]
A method that ends with [!] means it modifies it's own
instance (the original object). I will use the instance
method [swapcase!] , It swaps the sting case, doh!
a='I am A multiplied Cases String'
b=a.swapcase!
puts "#{a}\n#{b}"
This will print:
i AM a MULTIPLIED cASES sTRING
i AM a MULTIPLIED cASES sTRING
Notice [a] and [b], although different variables they both
reference the same Object in memory. To prove this run the
following code:
b[3]='X'
puts a+"\n"+b
This will print
i AX a MULTIPLIED cASES sTRING
i AX a MULTIPLIED cASES sTRING
Although I manipulated only [b], [a] also changed. So, the
methods that ends with a [!] modify themselves and return
their own instance, This is useful for chaining.
String Operators
Getting Familiar With the Common Methods of the String Class
The Postfixes of Methods: none,[!],[?]
|