1

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.

1
  • 5
    Because def1 within the interpolation is executed before to invoke to_s on it, after that it returns nil. Is the way puts works. Commented Aug 8, 2019 at 8:21

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

In order to print the string, puts has to know what the string is. In order to know what the string is in this particular line:

puts "some text #{def1}"

Ruby has to call def1 first. def1, in turn, calls puts to print something.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.