2

I can't figure out how to put the return of a method into a string. I had thought it would look like this,

def cat
 puts "Purrrrr..."
end

puts "The cat says #{cat}."

but this is not working. I also tried

puts "The cat says %s." % cat

and

puts "The cat says #{return.cat}."

also

puts "The cat says #{send.cat}."  

I kept trying stuff and looking things up.

2 Answers 2

8

It is working :

def cat
  "Purrrrr..."
end

puts "The cat says #{cat}."
# >> The cat says Purrrrr....

Why the below one is not giving the output as above :

def cat
 puts "Purrrrr..."
end

puts "The cat says #{cat}."
# >> Purrrrr...
# >> The cat says .

This is because you used puts "Purrrrr..." inside the method #cat. Now, inside the string interpolation method #cat has been called, and puts prints the the string "Purrrrr..." and returns nil. So puts "The cat says #{cat}." became puts "The cat says #{nil}.". Which results the output as :

The cat says .
            ^ 

"#{nil}" evaluates to an empty string(""). So the output is not as expected by you.

(arup~>~)$ irb
2.0.0-p0 :001 > nil.to_s
 => "" 
2.0.0-p0 :002 > "foo #{nil}"
 => "foo " 
2.0.0-p0 :003 > 

puts "The cat says #{return.cat}." and puts "The cat says #{send.cat}." are invalid ruby code, they will throw error. So Don't try this!

Hope it helps!

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

2 Comments

hmmm, that makes sense, but is there a way to call the method in a string, if it is a string, like the "purrrr..." ?
LOL, just saw what happened clearly, sorry, very confusing this stuff is!
1

In ruby you don't have to return a value explicitly. Last line result in a method will be returned by default.

In this case, the return value of 'puts' method is nil. So the return value of method 'cat' is nil.

If you are looking for a return string, you can just put a string at the last line of the method 'cat' as @Arup suggested. That will work.

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.