Identify number in the array and change to a string

0

I'm trying to change divisible numbers by 3 for a word within my array . I tried to add my if within array and with no result.

def code( n )
    if n % 3 == 0
    Array.new(n + 1) { |i| i }  
    end
    
asked by anonymous 17.10.2018 / 12:48

1 answer

0

You are not informing the word to be changed in the parameters
You need a Array with a size size and the word ( word ) that will replace the multiples of 3.

def code(size, word)
  Array.new(size + 1) { |i| i % 3 == 0 ? word : i }  
end

Result

  
    

code (10, 'ruby')

  
 ["ruby", 1, 2, "ruby", 4, 5, "ruby", 7, 8, "ruby", 10]

editing (another example)

minha_palavra = 'joão'
code(10, minha_palavra)

result

["joão", 1, 2, "joão", 4, 5, "joão", 7, 8, "joão", 10]

Tip It's a good practice to give better nines to your variables, instead of using code(n) try user code(tamanho) or code(size) so when you read you already know what's going on.

    
17.10.2018 / 18:36