简体   繁体   English

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

[英]Using a method return in a string in ruby

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. 我一直在努力寻找东西。

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 . 这是因为你在方法#cat使用了puts "Purrrrr..." Now, inside the string interpolation method #cat has been called, and puts prints the the string "Purrrrr..." and returns nil . 现在,在字符串插值方法#cat已调用#cat ,并且puts打印字符串"Purrrrr..."并返回nil So puts "The cat says #{cat}." 所以puts "The cat says #{cat}." became puts "The cat says #{nil}." 变成puts "The cat says #{nil}." . Which results the output as : 结果输出为:

The cat says .
            ^ 

"#{nil}" evaluates to an empty string( "" ). "#{nil}"计算为空字符串( "" )。 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}." puts "The cat says #{send.cat}." are invalid ruby code, they will throw error. 是无效的ruby代码,它们会抛出错误。 So Don't try this! 所以不要试试这个!

Hope it helps! 希望能帮助到你!

In ruby you don't have to return a value explicitly. 在ruby中,您不必显式返回值。 Last line result in a method will be returned by default. 默认情况下将返回方法中的最后一行结果。

In this case, the return value of 'puts' method is nil. 在这种情况下,'puts'方法的返回值为nil。 So the return value of method 'cat' is nil. 因此方法'cat'的返回值为零。

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. 如果你正在寻找一个返回字符串,你可以在方法'cat'的最后一行放一个字符串作为@Arup建议。 That will work. 那可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM