从Ruby函数返回一个字符串

在这个例子中:

def hello puts "hi" end def hello "hi" end 

第一个和第二个function有什么区别?

在Ruby函数中,当 显式定义返回值时, 函数将返回它评估最后一个语句 。 如果计算print语句,则函数将返回nil

因此,以下打印字符串hi返回 nil

 puts "hi" 

相反,以下返回字符串hi

 "hi" 

考虑以下:

 def print_string print "bar" end def return_string "qux" # same as `return "qux"` end foo = print_string foo #=> nil baz = return_string baz #=> "qux" 

但请注意,您可以printreturn相同function的内容:

 def return_and_print print "printing" "returning" # Same as `return "returning"` end 

以上将print字符串printing ,但返回字符串returning

请记住,您始终可以显式定义返回值

 def hello print "Someone says hello" # Printed, but not returned "Hi there!" # Evaluated, but not returned return "Goodbye" # Explicitly returned "Go away" # Not evaluated since function has already returned and exited end hello #=> "Goodbye" 

所以,总而言之,如果你想从一个函数中打印一些东西,比如说, print到控制台/日志 – 请使用print 。 如果要将该东西退出函数, 请不要print它 – 确保显式或默认返回它。

第一个使用puts方法将“hi”写入控制台并返回nil

第二个返回字符串“hi”并且不打印它

这是irb会话中的一个例子:

 2.0.0p247 :001 > def hello 2.0.0p247 :002?> puts "hi" 2.0.0p247 :003?> end => nil 2.0.0p247 :004 > hello hi => nil 2.0.0p247 :005 > def hello 2.0.0p247 :006?> "hi" 2.0.0p247 :007?> end => nil 2.0.0p247 :008 > hello => "hi" 2.0.0p247 :009 > 

把它打印到控制台。 所以

 def world puts 'a' puts 'b' puts 'c' end 

将’a’然后’b’然后’c’打印到控制台。

 def world 'a' 'b' 'c' end 

这将返回最后一件事,所以你只会看到’c’