ruby – Set中的yield以消除数组
|
我发现以下代码
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)
你做了,就是你把收益率.一旦你将这个收益率,现在方法是非常聪明的知道,它应该如此.在Messages.all.uniq_by {| h |行中你正在传递一个块{| h | h.body},并且在uniq_by的方法定义中,该块已被转换为Proc对象,yield为 证明: 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
阅读
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
