G
Gerald
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,
---------------------------------------------
#!/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,