1

For some reason I'm getting the error undefined method '%' for 1..100:Range when I run the following code:

[1..100].each do |x|
  if x % 3 == 0 && x % 5 == 0
    puts "CracklePop"
  elsif x % 3 == 0
    puts "Crackle"
  elsif x % 5 == 0
    puts "Pop"
  else
    puts x
  end
end

Any idea what's going on? Any help is much appreciated.

Eli
  • 299
  • 5
  • 18
  • 5
    I believe you misspelled ["fizz" and "buzz"](http://blog.adnanmasood.com/2010/04/21/the-fizz-buzz-programming-test/). – user229044 Apr 21 '14 at 18:17

3 Answers3

12

That's the wrong syntax for ranges.

You've made an array with 1 element, and that element is itself the range 1..100. What you've written is equivalent to [(1.100)]. You're iterating over the outer array one time, and setting x to (1..100)

You want (1..100).each, which invokes each on the range, not on an array containing the range.

user229044
  • 232,980
  • 40
  • 330
  • 338
1

By doing [1..100] you are not looping from 1 to 100 but on 1..100, which is a Range object, what you really want to do is:-

 (1..100).step do |x|
 if x % 3 == 0 && x % 5 == 0
     puts "CracklePop"
 elsif x % 3 == 0
     puts "Crackle"
 elsif x % 5 == 0
     puts "Pop"
 else
     puts x
 end
 end

Basically, Range represents an interval, you can iterate over Range as explained here, create an array from Range as explained here and more details on range can be found here.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
-1

Just as it says. 1..100 does not have a method %. The expression (1..100) % 3 is undefined.

sawa
  • 165,429
  • 45
  • 277
  • 381