【发布时间】:2014-02-17 04:57:11
【问题描述】:
在这个例子中:
def hello
puts "hi"
end
def hello
"hi"
end
第一个和第二个函数有什么区别?
【问题讨论】:
标签: ruby
在这个例子中:
def hello
puts "hi"
end
def hello
"hi"
end
第一个和第二个函数有什么区别?
【问题讨论】:
标签: ruby
在 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"
但是请注意,您可以通过print 和return 使用相同的功能:
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它 - 确保它被显式或默认返回。
【讨论】:
第一个使用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 >
【讨论】:
puts 将其打印到控制台。 所以
def world
puts 'a'
puts 'b'
puts 'c'
end
将打印 'a' 然后 'b' 然后 'c' 到控制台。
def world
'a'
'b'
'c'
end
这将返回最后一件事,所以你只会看到'c'
【讨论】: