Tech Support > Computer Hardware > Microprocessors > what method should a class provide for printf's %c ?
what method should a class provide for printf's %c ?
Posted by Gerald on July 29th, 2006


Consider the following snippet:

---------------------------------------------

#!/usr/bin/ruby

class Thing

def initialize(name)
@name = name
end

def to_s
@name
end

def to_i
@name.length
end
end

a = Bla.new("foo")

printf "%s\n", a
printf "%d\n", a
printf "%c\n", a

---------------------------------------------

This code breaks at the last line with the message :

../go7:22:in `printf': can't convert Thing into Integer (TypeError)

It seems that the printf conversion to %c tries to call a specific
method of my class to convert the object to the appropriate format. I am
a bit confused about the message "can't convert to integer", since the
to_i method is defined, and sucessfully called that the printf "%d"
line.

So, two questions arise

- what method am I supposed to provied for printf so it can handle the
'%s' format string

- How can I figure this out myself. It seems that printf is trying to
call something, but I have no way of telling exactly *what* it is
trying to do. Is there some kind of tracing/debugging that can be
switched on to see what's printf is trying to do ?

Thank you very much,


Posted by Gerald on July 29th, 2006


Gerald <gerr41@shoomann.com> wrote:

I'm very sorry, I posted to the wrong newsgroup.