I am relatively new to the rails syntax. I have a LogString class
class LogString < Array
I do the following with it
logs = LogString.new
logs.push 'this happened'
logs.push 'that happened'
whic开发者_Go百科h works fine. i want to be able to just write only
logs
to return what would be logs.join( ' | ' )
so i am looking for a syntax something like the method log_string here
class LogString < Array
def log_string
self.join( ' | ' )
end
end
but where log_string is automatically called when i simply write the class instance name: logs
how can i do that?
You can't just reference an object and have it call a method on the object, but you can get pretty close.
If you override the to_s
method (short for "to string"), you'll be able to do something like...
class LogString < Array
def to_s
self.join ' | '
end
end
log = LogString.new
log << "message one"
log << "message two"
puts "#{log}"
Add this:
def to_s
join '|'
end
This will work in templates and some I/O ops where #to_s is called. It won't work in irb unless you also modify #inspect
. (You could just have it call your new #to_s.)
精彩评论