user3043926 - 9 months ago 18

Ruby Question

I need to insert instead of numbers divisible by 3 , "d3" word. Also instead of numbers divisible by 5 ,"d5" word. How can I do it. I have tried here:

`puts "How many digits do u want to see?"`

number = gets.to_i

number.times do |n|

puts "#{n}"

if (n % 3 == 0)

puts "d3"

elsif (n % 5 == 0)

puts "d5"

end

end

If I enter number 7 the output must be :

`1`

2

d3

4

d5

d3

7

But I have different output when I enter number 7 :

`How many digits do u want to see?`

7

0

d3

1

2

3

d3

4

5

d5

6

d3

Where is my mistake?

Answer

Calling times on a range will throw the following error:

```
NoMethodError: undefined method `times' for 1..number:Range
```

Using times just like like in number.times will also start from 0 and end before the last number. Here is a possible solution which also adds a possibility of having a number being divisible by both 3 and 5.

```
puts "How many digits do u want to see?"
number = gets.to_i
(1..number).each do |n|
if (n % 3 == 0 && n % 5 == 0)
puts "..." # whatever message you like
elsif (n % 3 == 0)
puts "d3"
elsif (n % 5 == 0)
puts "d5"
else
puts n
end
end
```