Search code examples
javascriptruby-on-railsrubycode-translation

Modulus in Ruby always returning false


I need to "translate" the following loop from JavaScript to Ruby:

for(i=0;i<=b.length-1;i++){
  if(!(i%2)){
    c+=b[i]
  }
}

Here is how I tried to write the same in Ruby:

until i == b.length-1 do
  unless i%2 == true
    c += b[i]
    i += 1
  end  
end

The modulus operator in Ruby, however, seems to return false all the time; which renders the whole condition meaningless.

What am I doing wrong?


Solution

  • You should have:

    unless i%2 == 1
    

    or, equivalently:

    if i%2 == 0
    

    The reason of unexpected behavior is that Ruby treats all values (including 0) except false and nil as "truthy" in conditional statements.