S
Steven G. Harms
class String
def summon
puts "You summon: " + self
end
def summon2
puts "You summon: " + self.gsub('x','y')
end
def to_s
return "Atreyu"
end
end
"Artax".summon
"Artax".summon2
puts "Artax".to_s # reference 1
puts "Artax" # reference 2
This produces...
You summon: Artax
You summon: Artay
Atreyu
Artax
Now the "summon" methods indicate to me that by referencing self in
methods added to the String class, you can alter the string from
within itself. The question is, how can I get `puts "Artax" ` to
produce the same results as `puts "Artax"`. They are both Strings
and, as far as I understand it, to_s is what is used to get a String's
display value.
Question #1: Is there a way to references 1 and 2, supra, to do the
same thing?
Question #2: I thought perhaps I could do the magic on the assignment
operation. I'm not having too much luck with that, as yet.
If this is the best solution, could the responding individual please
be so gracious as to provide example code of how to override
assignment? I'm muddling about with my re-defined initialize
expecting an optional argument, but I've not figured out how to access
it properly.
Thanks,
Steven
def summon
puts "You summon: " + self
end
def summon2
puts "You summon: " + self.gsub('x','y')
end
def to_s
return "Atreyu"
end
end
"Artax".summon
"Artax".summon2
puts "Artax".to_s # reference 1
puts "Artax" # reference 2
This produces...
You summon: Artax
You summon: Artay
Atreyu
Artax
Now the "summon" methods indicate to me that by referencing self in
methods added to the String class, you can alter the string from
within itself. The question is, how can I get `puts "Artax" ` to
produce the same results as `puts "Artax"`. They are both Strings
and, as far as I understand it, to_s is what is used to get a String's
display value.
Question #1: Is there a way to references 1 and 2, supra, to do the
same thing?
Question #2: I thought perhaps I could do the magic on the assignment
operation. I'm not having too much luck with that, as yet.
If this is the best solution, could the responding individual please
be so gracious as to provide example code of how to override
assignment? I'm muddling about with my re-defined initialize
expecting an optional argument, but I've not figured out how to access
it properly.
Thanks,
Steven