Alle Wednesday 30 January 2008, Adam Akhtar ha scritto:
Hi if i want to count the number of times values are repeated in an
array how do i go about it...is there a method?
My solution is
list.sort
loop through list and compare one element to the next and count
repetitions.
is there a simpler way?
a = [2,4,6,2,1,3,4,6,4,1,2,3,1]
res = Hash.new(0)
a.each do |i|
res[i]+=1
end
p res
This creates a hash, which has a default value of 0 (that is, if a key isn't
included in the hash, the method returns 0). Then, there's an iteration on
all items of the array. For each element, the value of the hash item
corresponding to the array element is increased by one.
This can be written much more concisely as:
p a.inject(Hash.new(0)){|res, i| res[i]+=1; res}
in C i used the for loop a lot to loop through arrays but i notice that
in ruby using
list.each do |element|
..
..
end
is quite popular.
If i wanted to do someting like this:
if list[currElement] == list[currElement + 1]
Array#each_index or Array#each_with_index:
list.each_index do |i|
if list[i] == list[i+1]
...
endif
end
or
list.each_with_index do |element, i|
if e == list[i+1]
...
endif
end
Of course, in both cases you'd need to handle yourself the case of the last
element (in which case, list[i+1] will return nil).
Another possibility, if you only need to access the item after the current one
is to use each_cons:
require 'enumerator'
a = [1,2,3,4]
a.each_cons(2){|i| p i}
=>
[1, 2]
[2, 3]
[3, 4]
I hope this helps
Stefano
···
...
How would i go about writing that using list.each do |element|?
Any help greatly appreciated.