문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

Both in JavaScript and Ruby the modulus operator is expected to return an integer not a boolean:

2 % 2 
# => 0
3 % 2
# => 1

So, to check if i is even, you have to implement your condition like this:

unless i % 2 != 0
  # ...

However, for the purpose I think it's better to use one of the methods Integer#even? and Integer#odd?:

if i.even?
  #...

In Javascript, 0 and -0 are falsy values and therefore evaluate to false when doing comparisons. All other Numbers evaluate to true.

In Ruby, there is no implicit type conversion when comparing objects, and 0 evaluates to true. If you want to do your comparison in Ruby, you should use

if i%2 == 0

instead of your code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top