加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – `[]`如何与lambda一起使用

发布时间:2020-12-17 02:46:10 所属栏目:百科 来源:网络整理
导读:我有这个lambda(或正确的用法?)我理解.call的用法 def multi(m) lambda { |n| n * m }endtwo = multi(2)two.call(10) #= 20 #call the proc 但我想了解为什么/如何运作? two.(20) #= 40 two[20] #= 40 我不知道它应该或不应该起作用.大多数时候我使用方括
我有这个lambda(或正确的用法?)我理解.call的用法

def multi(m)
  lambda { |n| n * m }
end

two = multi(2)
two.call(10) #=> 20  #call the proc

但我想了解为什么/如何运作?

two.(20) #=> 40 
two[20] #=> 40

我不知道它应该或不应该起作用.大多数时候我使用方括号和数组.

解决方法

文档

prc[params,…] → obj

Invokes the block,setting the block’s parameters to the values in params using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array). Note that prc.() invokes prc.call() with the parameters given. It’s a syntax sugar to hide “call”.

For procs created using lambda or ->() an error is generated if the wrong number of parameters are passed to a Proc with multiple parameters. For procs created using Proc.new or Kernel.proc,extra parameters are silently discarded.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读