2016-05-12 38 views
1

我可以代替这个分配值仅如果不是零

le_one ||= load_le_other() 

我如何取代这个:有比这以外的东西

le_other = load_le_other() 
le_one = le_other if le_other 

le_other = load_le_other() 
le_one = le_other || le_one 

load_le_other调用两次是昂贵的。目标是让它成为一个班轮。

+3

我没有看到'load_le_other'被调用了两次。 – AlexN

+0

我觉得好奇的是,有那么多读者解释为“load_le_other'调用两次的代价很大”,这意味着OP的代码会将该方法调用两次,并且要避免。把它解释为意味着单线不应该将这种方法称为两次是不是更有意义? –

回答

3

替换此:

le_one = load_le_other() || le_one 
+1

这就是OP明确表示要避免的原因。 – sawa

+0

@sawa很好,可能会等待lucas –

+0

这是一次只能调用'load_le_other()'的单线程。如果这不完全是问题,那么这个问题需要编辑。 –

0

如果load_le_other()不能返回false

le_one = le_other = load_le_other() 

注意,如果

le_other = load_le_other() 
    #=> nil 
le_one = le_other if le_other 
    # le_one = nil if nil 
    #=> nil