thinkingmonster
thinkingmonster

Reputation: 5433

Why is the method output printed first?

I wrote the following:

greeting="i am awesome"
puts("I was saying that #{greeting}")
# => I was saying that i am awesome

When I change it to this:

def showman
  print("I am awesome ")
end
puts("I was saying that #{showman}")
# => I am awesome I was saying that 

why is the method output printed first, and then the string? Why is it not printing like "I was saying that I am awesome"? What can I do to make the output be as such?

If I modify the showman function to:

def showman
  return ("I am awesome ")
end

then it gives the desired output. Why is the use of return in this way making difference to the output?

Upvotes: 0

Views: 31

Answers (1)

sawa
sawa

Reputation: 168209

In first output why method output is printed first and then the string.

In order to evaluate the string, showman is evaluated before the whole string is evaluated, which prints "I am awesome ".

Why its not printing like "I was saying that I am awesome"

Because print returns nil, and interpolating nil in a string evaluates to an empty string ("#{showman}""#{nil}"""). Without print, the showman method returns the string "I am awesome ".

Why is the use of return in this way making difference to the output?

It is not the use of return that is making the difference. It is the absence of print that is making the difference.

Upvotes: 3

Related Questions