What is the equivalent of C++ "this"?

L

lalawawa

I want to write a method within class Array that will put single
quotes around every element of the array.

"this" doesn't work in Ruby. If it did I would write

class Array
def quote
length.times {|i| this = "'" + this.to_s + "'"
end
end

Ruby doesn't know what I mean when I say "this". How do I call the []
operator when I'm in the array class and have the language realize I'm
not building a list?
 
T

Tor Erik Linnerud

lalawawa wrote:

In Ruby, "this" is called self.

def quote
length.times {|i| self = "'" + self.to_s + "'"
end

A more idiomatic Ruby way to achieve the same thing would be use map or
map!. The later method will replace each element of the array with the
value produced in the block given.

def quote
map!{|element| "'#{element}'"}
end

Tor Erik
 
A

Allan Wind

Ruby doesn't know what I mean when I say "this". How do I call the []
operator when I'm in the array class and have the language realize I'm
not building a list?

self


/Allan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top