Search code examples
rubystring-interpolation

Ruby: String interpolation prints the function first when called second


Here is my short program

def def1()
  x = 1
  puts x
end

def def2()
  y = 2
  puts y
end

puts "some text #{def1}"
puts "some text #{def2}"

The outcome of this example...

1
some text 
2
some text

I don't understand why this puts in this order and not "sometext" first.


Solution

  • Because the string is created first, which means calling def1, and then the whole string is passed into puts.

    We can expand puts "some text #{def1}" out to understand.

    string = "some text " + def1.to_s
    puts string
    

    As you can see, def1 is called to create the string. def1 prints out 1 itself, it does not return anything (it returns nil). Then the whole string is printed.

    That's how all function calls work. The arguments are evaluated, the the function is called.

    You'd need to call def1 after printing the prefix.

    print "some text "
    def1
    

    This is a reason why it's often better to have a function return a value rather than print it itself.