From: Vitaliy Yanchuk on 20 Jul 2010 09:47 Hello, everyone. Would be grateful if someone can tell, how can I do shortly (mb with one method) from such example array ["a", "b", "a", "c", "c", "b", "b"] The result a => 2 b => 3 c => 2 So, to count number of occurances -- Posted via http://www.ruby-forum.com/.
From: Jean-Julien Fleck on 20 Jul 2010 10:00 Hello, > Would be grateful if someone can tell, how can I do shortly (mb with one > method) from such example array > > ["a", "b", "a", "c", "c", "b", "b"] > > The result > a => 2 > b => 3 > c => 2 > > So, to count number of occurences >> arr = ["a", "b", "a", "c", "c", "b", "b"] => ["a", "b", "a", "c", "c", "b", "b"] >> h = Hash.new(0) ; arr.each {|e| h[e] += 1}; p h {"a"=>2, "b"=>3, "c"=>2} => nil Cheers, -- JJ Fleck PCSI1 Lycée Kléber
From: Vitaliy Yanchuk on 20 Jul 2010 10:25 Jean-Julien Fleck, thanks. Maybe have an idea of a one-line version? :) -- Posted via http://www.ruby-forum.com/.
From: Jean-Julien Fleck on 20 Jul 2010 10:44 2010/7/20 Vitaliy Yanchuk <fuksito(a)gmail.com>: > Jean-Julien Fleck, thanks. > Maybe have an idea of a one-line version? :) Well: quite the same using inject: arr.inject(Hash.new(0)) {|h,e| h[e]+= 1; h} It all depends on what you call 'one-line' :o) Cheers, -- JJ Fleck PCSI1 Lycée Kléber
From: Vitaliy Yanchuk on 20 Jul 2010 10:58 Jean-Julien Fleck wrote: > 2010/7/20 Vitaliy Yanchuk <fuksito(a)gmail.com>: >> Jean-Julien Fleck, thanks. >> Maybe have an idea of a one-line version? :) > > Well: quite the same using inject: > > arr.inject(Hash.new(0)) {|h,e| h[e]+= 1; h} > > It all depends on what you call 'one-line' :o) > > Cheers, Wow, Inject is cool method, thanks ! In my mind one-line is that dows not have semi-coloms or new lines of course -- Posted via http://www.ruby-forum.com/.
|
Next
|
Last
Pages: 1 2 3 4 Prev: undefined method `call' for nil:NilClass (NoMethodError) Next: Ruby Shoes tray icon? |