使用方法返回ruby中的字符串

rya*_*ker 2 ruby string methods return

我无法弄清楚如何将方法的返回放入字符串中.我以为它看起来像这样,

def cat
 puts "Purrrrr..."
end

puts "The cat says #{cat}."
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我也试过了

puts "The cat says %s." % cat
Run Code Online (Sandbox Code Playgroud)

puts "The cat says #{return.cat}."
Run Code Online (Sandbox Code Playgroud)

puts "The cat says #{send.cat}."  
Run Code Online (Sandbox Code Playgroud)

我一直在努力寻找东西.

Aru*_*hit 9

这是工作 :

def cat
  "Purrrrr..."
end

puts "The cat says #{cat}."
# >> The cat says Purrrrr....
Run Code Online (Sandbox Code Playgroud)

为什么下面的一个没有给出如上的输出:

def cat
 puts "Purrrrr..."
end

puts "The cat says #{cat}."
# >> Purrrrr...
# >> The cat says .
Run Code Online (Sandbox Code Playgroud)

这是因为你puts "Purrrrr..."在方法中使用了#cat.现在,在字符串插值方法#cat内部已经调用,并puts打印字符串"Purrrrr..."并返回nil.所以puts "The cat says #{cat}."成了puts "The cat says #{nil}.".结果输出为:

The cat says .
            ^ 
Run Code Online (Sandbox Code Playgroud)

"#{nil}"计算为空字符串("").所以输出并不像你预期的那样.

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

puts "The cat says #{return.cat}."并且puts "The cat says #{send.cat}."是无效的ruby代码,它们会抛出错误.所以不要试试这个!

希望能帮助到你!