2012-10-30 20 views
0

我徘徊隱含的返回值,如果它使用[]=方法是OK使用Ruby的從[] =

[]=使用rb_hash_aset時即可使用Ruby的隱式的返回值,它返回val - http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-5B-5D-3D

這裏是一個小的代碼來證明我的意思:

require 'benchmark' 
CACHE = {} 
def uncached_method(key) 
    warn "uncached" 
    rand(100) 
end 
def cached(key) 
    CACHE[key] || (CACHE[key] = uncached_method(key)) 
end 
def longer_cached(key) 
    return CACHE[key] if CACHE[key] 
    CACHE[key] = uncached_method(key) 
    CACHE[key] 
end 

Benchmark.bm(7) do |x| 
    y = rand(10000) 
    cached(y) 
    x.report("shorter:") { 10000000.times do cached(y) end } 
    x.report("longer:") { 10000000.times do longer_cached(y) end } 
end 
當然 longer_cached

是慢,因爲它做了兩個哈希查詢返回緩存值,但磨片ñ你一行一行地閱讀它,然後cached方法更有意義。

我認爲使用隱式返回是使ruby真棒的事情之一,但我總是質疑他們在設置值時的使用。

所以我的問題是:你會使用從(hash[key] = val)隱含返回?

+0

爲什麼不使用'||'有意義?與自然語言不一樣嗎?例如,用英文,「(給我)'CACHE [key]',或者分配它,(然後把它給我)」。 – sawa

回答

1

只是因爲沒有人提到它到目前爲止:你是不是依靠Hash#[]=返回值。那返回值被忽略反正:

class ReturnFortyTwo 
    def []=(*) 
    return 42 
    end 
end 

r = ReturnFortyTwo.new 

r[23] = 'This is the value that is going to be returned, not 42' 
# => 'This is the value that is going to be returned, not 42' 

在Ruby中,賦值表達式總是評估到被分配的值。沒有例外。這是由語言規範保證的。所以,我不認爲依靠這個有什麼不妥。

0

在這種情況下,較短的一個是可取的。在子表達式中使用的=被忽略,但這裏沒關係。

2

在這種情況下,您也可以使用||=運算符。

CACHE[key] ||= uncached_method(key) 

這是一個很常見的成語。

0

我會保持它的簡單和乾淨越好(它的速度更快,太):

def cached(key) 
    value = CACHE[key] 
    unless value 
    value = uncached_method(key) 
    CACHE[key] = value 
    end 
    value 
end