Using a method return in a string in ruby

methods, return, ruby, string

Solution

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!

Problem

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.

Original source