`

也说说ruby inject

阅读更多
其实,没有什么太多说的,IE有的先链接过来

http://biyeah.iteye.com/blog/1286449

http://www.iteye.com/topic/56291

下面的总结的挺好,

完了来回顾一下inject方法两种用法:
enum.inject(init_value) {|memo,obj|  block}
enum.inject{ |memo,obj| block }


第一种,memo以init_value为初始值
第二种,memo以enum里的第一个元素为初始值。


然后,inject可以这么写
(1..4).inject(&:+)


涵义是

{|memo, a| memo.send(sym, a)}


和map那个用法一样

 def tag_names
    @tag_names || tags.map(&:name).join(' ')
  end


涵义是:

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args
    end
  end
end


也可以带index的执行
%w(a b c).each_with_index.inject([]){|result, (value,index)| result << value + index.to_s}



所以,一组值的时候

User.all.inject(0){|sum,user|sum += user.followers.count}

或者
User.all.map(&:count).inject(&:+)

其实
User.sum(:filed)



------------------------------------------华丽啥分割----------------------------------------------------------------
挺好的东西收到这吧
精细duck typing控制
duck typing的精神就是行为决定类型,而不是相反

a = []  
#不用  
if a.kind_of? Array then a << 1  
if a.instance_of? Array then a << 1  
#而用  
if a.respond_to? :<< then a << 1  



获取metaclass
这也比较常见了,各种动态伎俩的开始

sing = class << self; self; end  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics