John John - 6 months ago 10
Ruby Question

how to perform custom operations on an array to get a specific result in ruby using map or by using some enumarator methods?

i have an

array
late_mark_array
which will contain the values like
["yes","yes","yes","yes","yes","yes","no","no","yes","yes","yes","yes","no"]
. these indicates an
employee
consecutive
late marks
in a particular
month
. in this array
"yes"
indicates
late
.
"no"
indicates
no late
. here i want implement
penalties
for
lates
. if an
employee
is late for
consecutive three
days,that means in above
array
if there are three consecutive
"yes"
marks then i want to increment the
penalty
count by one. and after the
three
consecutive late marks again if there is a
late
mark, means
"yes"
is present, then at that time penalty needs to be incremented by one for each
"yes"
, after the consecutive
lates
occurred. so as per this
logic
the
penalty
to the above employee should be
"6"
. donot know how to implement this logic on the above array.

Answer

You can use .each_cons(3) and then count the number of slices containing all "yes":

irb> input = ["yes","yes","yes","yes","yes","yes","no","no","yes","yes","yes","yes","no"]
=> ["yes", "yes", "yes", "yes", "yes", "yes", "no", "no", "yes", "yes", "yes", "yes", "no"]
irb> input.each_cons(3).count { |slice| slice.all? { |item| item == "yes" } }
=> 6
Comments