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

ruby – Set中的yield以消除数组

发布时间:2020-12-17 02:46:59 所属栏目:百科 来源:网络整理
导读:我发现以下代码 here用于消除数组中的重复记录: require 'set'class Array def uniq_by seen = Set.new select{ |x| seen.add?( yield( x ) ) } endend 我们可以使用上面的代码如下: @messages = Messages.all.uniq_by { |h| h.body } 我想知道调用该方法
我发现以下代码 here用于消除数组中的重复记录:

require 'set'

class Array
  def uniq_by
    seen = Set.new
    select{ |x| seen.add?( yield( x ) ) }
  end
end

我们可以使用上面的代码如下:

@messages = Messages.all.uniq_by { |h| h.body }

我想知道调用该方法时会发生什么以及会发生什么.有人可以解释上面代码的内部结构吗?在uniq_by方法中,我们没有做任何事来处理块参数.如何通过uniq_by方法处理传递的参数?

解决方法

在Ruby中,当你将yield关键字放在任何方法(比如#bar)中时,你明确地告诉#bar,你将使用方法#bar的块.所以yield知道,在方法块内部将转换为 Proc对象,并且yield必须调用该Proc对象.

示例:

def bar
   yield
end

p bar { "hello" } # "hello" 
p bar # bar': no block given (yield) (LocalJumpError)

In the uniq_by method,we did not do anything to handle block argument. How is the passed argument handled by uniq_by method?

你做了,就是你把收益率.一旦你将这个收益率,现在方法是非常聪明的知道,它应该如此.在Messages.all.uniq_by {| h |行中你正在传递一个块{| h | h.body},并且在uniq_by的方法定义中,该块已被转换为Proc对象,yield为Proc#call.

证明:

def bar
   p block_given? # true
   yield
end

bar { "hello" } # "hello"

更好理解:

class Array
  def uniq_by
    seen = Set.new
    select{ |x| seen.add?( yield( x ) ) }
  end
end

和…一样

class Array
  def uniq_by
    seen = Set.new
    # Below you are telling uniq_by,you will be using a block with it
    # by using `yield`.
    select{ |x| var = yield(x); seen.add?(var) }
  end
end

阅读yield的文档

Called from inside a method body,yields control to the code block (if any) supplied as part of the method call. If no code block has been supplied,calling yield raises an exception. yield can take an argument; any values thus yielded are bound to the block’s parameters. The value of a call to yield is the value of the executed code block.

(编辑:李大同)

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

    推荐文章
      热点阅读