As you know, there is a method String#reverse to reverse a string. I understand you are not to use that method, but instead write your own, where the method's argument is the string to be reversed. Others will suggest ways you might do that.
As you are new to Ruby, I thought it might be instructive to show you how you could write a new method for the String
class, say, String#my_reverse
, that behaves exactly the same as String#reverse
. Then for the string "three blind mice"
, we would have:
"three blind mice".reverse #=> "ecim dnilb eerht"
"three blind mice".my_reverse #=> "ecim dnilb eerht"
To create a method without arguments for the String class, we normally do it like this:
class String
def my_method
...
end
end
We invoke my_method
by sending it a receiver that is an instance of the String
class. For example, if write:
"three blind mice".my_method
we are sending the method String#my_method
to the receiver "three blind mice"
. Within the definition of the method, the receiver is referred to as self
. Here self
would be "three blind mice"
. Similarly, just as the second character (at offset 1) of that string is "three blind mice"[1] #=> "h"
, self[1] #=> "h"
. We can check that:
class String
def my_method
puts "I is '#{self}'"
(0...self.size).each { |i| puts self[i] }
end
end
"three blind mice".my_method
would print:
I is 'three blind mice'
t
h
r
e
e
b
...
c
e
The method my_reverse
is almost the same:
class String
def my_reverse
sz = self.size
str = ''
(0...sz).each { |i| str << self[sz-1-i] }
str
end
end
"three blind mice".my_reverse
#=> "ecim dnilb eerht"
You can think of self
as a variable whose value is the receiver, but unlike a variable, you cannot reassign self to a different object. For example, we can write x = 1; x = 'cat'
, but we cannot write self = 'cat'
. As we have already seen, however, we can change the references self makes to other objects, such as self[1] = 'r'
.