可以使用ruby';s来自[]的隐式返回值=
我想知道在使用可以使用ruby';s来自[]的隐式返回值=,ruby,Ruby,我想知道在使用[]=方法时是否可以使用ruby的隐式返回值 []=使用rb\u hash\u aset并返回val- 下面是一个小代码来演示我的意思: require 'benchmark' CACHE = {} def uncached_method(key) warn "uncached" rand(100) end def cached(key) CACHE[key] || (CACHE[key] = uncached_method(key)) end def long
[]=
方法时是否可以使用ruby的隐式返回值
[]=
使用rb\u hash\u aset
并返回val
-
下面是一个小代码来演示我的意思:
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\u cached
速度较慢,因为它会执行两次哈希查找以返回缓存的值,但是当您逐行读取它时,它比cached
方法更有意义
我认为使用隐式返回是ruby令人敬畏的原因之一,但我一直质疑它们在设置值时的用途
所以我的问题是:您会使用来自
(hash[key]=val)
的隐式返回吗?在这种情况下,较短的返回更可取。通常,子表达式中使用的=
是不受欢迎的,但在这里没有关系。在这种情况下,较短的子表达式更可取。通常不赞成在子表达式中使用=
,但在这里没有问题。在这种情况下,您也可以使用|124;=
操作符
CACHE[key] ||= uncached_method(key)
这是一个非常常见的习惯用法。在本例中,您还可以使用
|124;=
运算符
CACHE[key] ||= uncached_method(key)
这是一个非常常见的习惯用法。我会让它尽可能简单和干净(它也更快):
我会让它尽可能简单和干净(它也更快):
只是因为到目前为止还没有人提到它:您不依赖于
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中,赋值表达式的计算结果始终是被赋值的值。也不例外。语言规范保证了这一点。因此,我不认为依赖它有什么错。只是因为到目前为止还没有人提到它:您没有依赖于
散列#[]=
的返回值。该返回值仍将被忽略:
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中,赋值表达式的计算结果始终是被赋值的值。也不例外。语言规范保证了这一点。因此,我认为依赖它没有什么错。为什么使用
|
没有意义?这和自然语言不一样吗?例如,在英语中,“(给我)CACHE[key]
,或者分配它(然后给我)”。为什么使用|
没有意义?这和自然语言不一样吗?例如,在英语中,“(给我)CACHE[key]
,或者分配它(然后给我)”。