New to Ruby here and trying to output the contents of an instance for a class I’ve created. I don’t think it should matter, but known_var in the following is being retrieved from an array. The line I am running is simply:
for known_var in @known_variables
puts "known_var is #{known_var}"
The result I am getting is consistently in the format:
resistance = 2200 Ohmsknown_var is #<Variable:0x000001e21047f920>
The class does have a customized to_s definition, which why the first chunk is formatted as it is:
def to_s
if @value == nil
print "#@full_name = 0"
else print "#@full_name = #@value #@unit"
end
end
However, I’m not sure why this is showing up before the "known_var is" part of the string. It looks similar if I specify:
puts "known_var is #{known_var}"
minus the Variable part, which makes sense:
amperage = 12 Aknown_var is
Is there something that should be done differently if I want it to just output the text in the order it’s provided in puts: "known_var is XXXXXX"?
I’ve run some searches to see if I can find an explanation (without luck so far). I can work around it by splitting the puts into two separate lines, but that’s not what I’m looking to do, and more importantly, I want to understand why puts is ordering things in the way it is here.
>Solution :
Avoid printing statements within the to_s method; instead, consider the updated to_s method below.
def to_s
if @value == nil
"#@full_name = 0"
else
"#@full_name = #@value #@unit"
end
end