Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby Interpolation Results in Out-of-Order Output

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading