从Ruby函数返回一个字符串

fra*_*ort 0 ruby

在这个例子中:

def hello
  puts "hi"
end

def hello
  "hi"
end
Run Code Online (Sandbox Code Playgroud)

第一个和第二个功能有什么区别?

zea*_*soi 8

在Ruby函数中,当 显式定义返回值时,函数将返回它评估最后一个语句.如果只有一个print声明进行评估,该函数将返回nil.

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

puts "hi"
Run Code Online (Sandbox Code Playgroud)

相反,以下返回字符串hi:

"hi"
Run Code Online (Sandbox Code Playgroud)

考虑以下:

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"
Run Code Online (Sandbox Code Playgroud)

但是请注意,你可以printreturn一些同样的功能的:

def return_and_print
  print "printing"
  "returning" # Same as `return "returning"`
end
Run Code Online (Sandbox Code Playgroud)

上面将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"
Run Code Online (Sandbox Code Playgroud)

所以,总而言之,如果你想从一个函数中打印一些东西,比如说,打印到控制台/日志 - 使用print.如果你想从函数中返回那个东西,不要只是print- 确保它是显式地或默认返回的.