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[i] = “’” + this[i].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?
lalawawa wrote:
In Ruby, “this” is called self.
def quote
length.times {|i| self[i] = "'" + self[i].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
On 2010-01-18T10:50:06, lalawawa wrote:
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