lundi 19 septembre 2016

How to get back the original element after split and inject?

Time to ask the experts,
I am hammered with a piece of code I am trying to get to the bottom of. I seemed to have isolated the two most important pieces, but the whole things isn't working.

def revrot(str, sz)
    return "" if sz <= 0 || str == nil
    y =  str.scan(/.{1,sz}/).select{|n| n == sz}
    x = ""
    for i in y
        if  i.split(//).collect{|n| n.to_i ** 3}.inject(:+) % 2 == 0 
            x << i.reverse!
        else
           x << (i[-1] << i.slice(0..-2))
        end
    end
   return x
end

puts revrot("123456987654", 6)

My questions are as follows. The scanned chunks of string numbers must either be reversed, or rotated(last element brought to the front) returning a new string of fixnums. If one chunk is less than sz, it is deleted.

1)Can my first block, select, take the variable sz? I need to get rid of an element that is less than sz.

2) After I perform the check , 'i' is cubed, summed, divisible by two.how can I get back my original string of numbers that is 'i'? So I can continue performing the subsequent actions on it, which is reverse? I want to do the check, but not change the original element in the array, 'i'. The else part is the rotation, which works in irb. Any input at all, is much appreciated.

thanks

Aucun commentaire:

Enregistrer un commentaire