Hi Experts,
arr = [1, 2, 3, 5, 5, 2, 5]
is that possible to find whats the count of an value inside an array
“arr”
for example
1 - 1
2 - 2
3 - 1
5 - 3
is that possible?
plz help me guys, its my requirement for specific reasons.
regards,
Bala
Hi Experts,
arr = [1, 2, 3, 5, 5, 2, 5]
is that possible to find whats the count of an value inside an array
“arr”
for example
1 - 1
2 - 2
3 - 1
5 - 3
is that possible?
plz help me guys, its my requirement for specific reasons.
regards,
Bala
Hi,
On 29 Okt., 07:06, Bala [email protected] wrote:
arr = [1, 2, 3, 5, 5, 2, 5]
is that possible to find whats the count of an value inside an array
“arr”
One way could be something like this.
arr = [1, 2, 3, 5, 5, 2, 5]
counts = {}
arr.each do |item|
begin
counts[item] = counts[item] + 1
rescue
counts[item] = 1
end
end
counts.each {|k, v| puts “#{k}: #{v}”}
But there probably is some more concise way.
Lutz
Hi Lutz,
I got it, but i tried in way using like this
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1 }
k
end
end
a = %w[N1100, N2200, N2200, N1100, N4400]
items = a.count
puts items.inspect
Bala wrote:
Hi Lutz,
I got it, but i tried in way using like this
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1 }
k
end
enda = %w[N1100, N2200, N2200, N1100, N4400]
items = a.count
puts items.inspect
inject is QUITE a powerful tool as well
http://www.ruby-doc.org/core/classes/Enumerable.html#M003171
arr = [1, 2, 3, 5, 5, 2, 5]
arr.inject(Hash.new(0)){|hsh,arr_elm| hsh[arr_elm]+=1 }
worth checking out, a lot of functionality in a one-liner… worth
knowing exists, at the least. hth -
shai
Shai R. wrote:
Shai R. wrote:
Bala wrote:
Hi Lutz,
I got it, but i tried in way using like this
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1 }
k
end
end…btw, these types of questions (pure ruby vs ruby on rails) are great
to ask on the ruby forum - that’s what it is for, and the real experts
seem to lay around there (i’ve seen a DHH and even matz shmooze around
there occasionally)
…and, for example, a thread i’ve just found on
the ruby-forum right at this moment -
http://www.ruby-forum.com/topic/129613
Shai R. wrote:
Bala wrote:
Hi Lutz,
I got it, but i tried in way using like this
class Array
def count
k=Hash.new(0)
self.each{|x| k[x]+=1 }
k
end
end
…btw, these types of questions (pure ruby vs ruby on rails) are great
to ask on the ruby forum - that’s what it is for, and the real experts
seem to lay around there (i’ve seen a DHH and even matz shmooze around
there occasionally)
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs