Identify number in array and change to a string

Asked

Viewed 182 times

0

I’m trying to trade divisible numbers for 3 for a word inside my array. I tried to add my if within the array and with no result.

def code( n )
    if n % 3 == 0
    Array.new(n + 1) { |i| i }  
    end

1 answer

0

You are not giving the word to be exchanged in the parameters
You need a Array of 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

Upshot

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)

outworking

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

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

  • Got it ! Where do I declare then to replace with the word "ruby" in the case ? I tried here but informed me an error saying 'Wrong number of Arguments (1 for 2)"

  • Example code(10, 'word you want'). Take the code I put above and change the second parameter.

  • Putting after word, like > word: code(10, 'Ruby')? Sorry for the questions, I’m still new to Ruby

  • word: code(10, 'Ruby') is wrong! the right is to execute only the following code (10, 'qualquer_palatra') -I added another description up there

  • I understood how you did ! But it’s not going, returns me error. I set right inside the Array. I wanted him to check on his own and change, like you did.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.