2014-02-17 26 views
0

返回一個字符串,在這個例子中:從Ruby的功能

def hello 
    puts "hi" 
end 

def hello 
    "hi" 
end 

什麼是第一和第二函數之間的區別?

回答

8

在Ruby函數,當返回值爲明確定義,函數將返回最後聲明它評估。如果只有 a 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出來的東西同樣的功能:

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它 - 確保它返回,顯式或默認。

+0

好東西。很徹底。 @zeantsoi – franksort

1

第一個使用的puts方法寫「你好」到控制檯,並返回nil

第二個返回字符串「喜」,不打印

下面是一個例子一個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 > 
0

將它打印到控制檯。 所以

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

將打印 '一',那麼 'B',那麼 'C' 到控制檯。

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

這將返回的最後一件事,所以你只能看到「C」