Problems with Modulo operator Ruby: Why am I getting "undefined method `%' for 1..100:Range"?

StackOverflow https://stackoverflow.com/questions/23203169

  •  07-07-2023
  •  | 
  •  

質問

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.

役に立ちましたか?

解決

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.

他のヒント

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.

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top