Ruby on Rails Monday, January 21, 2013

I tend to use a method like:


module Enumerable
  # Returns a Hash keyed by the value of the block to the number times that
  # value was returned.  If you have experience with the #group_by from
  # ActiveSupport, this would be like .group_by(&block).map{|k,a|[k,a.size]}
  # (except it is a Hash rather than an Array).
  def count_by
    counts = Hash.new(0)
    each {|e| counts[block_given? ? yield(e) : e] += 1}
    counts
  end
end

$ irb -r ./enumerable
irb1.9.3> a=[ 'casual','sick','casual','sick','casual','sick','casual','sick' ] 
#1.9.3 => ["casual", "sick", "casual", "sick", "casual", "sick", "casual", "sick"]
irb1.9.3> a.count_by
#1.9.3 => {"casual"=>4, "sick"=>4}

This keeps you from iterating over the source multiple times, too.

-Rob

On Jan 21, 2013, at 1:37 AM, Ashokkumar Yuvarajan wrote:

thanks :)
On Mon, Jan 21, 2013 at 12:06 PM, bala kishore pulicherla <balumca21@gmail.com> wrote:
a.count("casual")

On Mon, Jan 21, 2013 at 12:03 PM, Maddy <ashokkumar@shriramits.com> wrote:
Hi Everyone,

Good Day,

a=[ 'casual','sick','casual','sick','casual','sick','casual','sick' ] 

I need to collect casual's count and sick's count like,
Caual :4
Sick :4

Thank you,

--
"Attitude is a little thing that makes a big difference"

Thanks & Regards
Ashokkumar.Y
ROR-Developer
email : ashokkumar@shriramits.com
Shriramits

No comments:

Post a Comment